### Manage Standard IO Streams Source: https://context7.com/madelson/medallionshell/llms.txt Provides examples for reading and writing to standard input, output, and error streams directly. ```csharp using Medallion.Shell; var command = Command.Run("interactive-program"); // Write to standard input (text) command.StandardInput.Write("some text"); command.StandardInput.WriteLine("a line of text"); await command.StandardInput.WriteLineAsync("async line"); // Write raw bytes to standard input byte[] data = new byte[100]; command.StandardInput.BaseStream.Write(data, 0, data.Length); // Read from standard output (text) string line = command.StandardOutput.ReadLine(); string allOutput = command.StandardOutput.ReadToEnd(); string asyncLine = await command.StandardOutput.ReadLineAsync(); // Read raw bytes from standard output byte[] buffer = new byte[1024]; int bytesRead = command.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length); // Read from standard error string errorLine = command.StandardError.ReadLine(); byte[] errorBytes = new byte[256]; command.StandardError.BaseStream.Read(errorBytes, 0, errorBytes.Length); // Close standard input when done writing command.StandardInput.Dispose(); // Enumerate output lines foreach (string outputLine in command.StandardOutput.GetLines()) { Console.WriteLine(outputLine); } ``` -------------------------------- ### Manage process execution and results Source: https://github.com/madelson/medallionshell/blob/master/README.md Demonstrates creating a command, waiting for completion, and inspecting the result. ```C# // create a command via Command.Run var command = Command.Run("executable", "arg1", "arg2", ...); // wait for it to finish command.Wait(); // or... var result = command.Result; // or... result = await command.Task; // inspect the result if (!result.Success) { Console.Error.WriteLine($"command failed with exit code {result.ExitCode}: {result.StandardError}"); } ``` -------------------------------- ### Configure Reusable Shell Settings Source: https://context7.com/madelson/medallionshell/llms.txt Create a Shell instance to define default options like timeouts, working directories, and environment variables for multiple commands. ```csharp using Medallion.Shell; // Create a shell with default options for all commands var shell = new Shell(options => options .ThrowOnError() .Timeout(TimeSpan.FromMinutes(5)) .WorkingDirectory("/home/user/project") .EnvironmentVariable("ENV", "production")); // All commands run through this shell inherit the configuration var result1 = shell.Run("git", "status").Result; var result2 = shell.Run("npm", "install").Result; // Override options for specific commands var customResult = shell.Run("slow-task", options: options => options.Timeout(TimeSpan.FromMinutes(30))); // Use Command() option to set up piping/redirection via shell var shellWithRedirect = new Shell(options => options .Command(cmd => cmd.RedirectTo(new FileInfo("output.log")))); // Use the default shell (no special configuration) var defaultResult = Shell.Default.Run("echo", "hello").Result; ``` -------------------------------- ### Configure Command Options Source: https://context7.com/madelson/medallionshell/llms.txt Shows how to customize process execution using options like timeouts, environment variables, working directories, and cancellation tokens. ```csharp using Medallion.Shell; using System.Text; // Throw exception on non-zero exit code var command = Command.Run("git", new[] { "status" }, options => options.ThrowOnError()); // Set working directory Command.Run("ls", options: options => options.WorkingDirectory("/home/user/project")); // Set timeout (process killed after timeout) Command.Run("long-running-task", options: options => options.Timeout(TimeSpan.FromSeconds(30))); // Cancellation token support var cts = new CancellationTokenSource(); Command.Run("some-process", options: options => options.CancellationToken(cts.Token)); // Later: cts.Cancel() will kill the process // Environment variables Command.Run("my-app", options: options => options .EnvironmentVariable("MY_VAR", "value") .EnvironmentVariables(new Dictionary { ["API_KEY"] = "secret", ["DEBUG"] = "true" })); // Custom encoding for IO streams Command.Run("unicode-app", options: options => options.Encoding(Encoding.UTF8)); // Advanced ProcessStartInfo configuration Command.Run("my-app", options: options => options.StartInfo(psi => { psi.Domain = "MYDOMAIN"; psi.UserName = "user"; })); // Disable automatic disposal (for accessing Process object later) var cmd = Command.Run("notepad", options: options => options.DisposeOnExit(false)); // Now you can access cmd.Process safely ``` -------------------------------- ### Configuring Command Options Source: https://github.com/madelson/medallionshell/blob/master/README.md Sets execution options such as error handling, working directory, and timeouts during command initialization. ```C# Command.Run("foo.exe", new[] { "arg1" }, options => options.ThrowOnError()...); ``` -------------------------------- ### Execute Commands with MedallionShell Source: https://context7.com/madelson/medallionshell/llms.txt Demonstrates basic synchronous and asynchronous command execution, including argument handling and result retrieval. ```csharp using Medallion.Shell; // Simple command execution var command = Command.Run("git", "status"); command.Wait(); // Access the result var result = command.Result; Console.WriteLine($"Exit Code: {result.ExitCode}"); Console.WriteLine($"Success: {result.Success}"); Console.WriteLine($"Output: {result.StandardOutput}"); Console.WriteLine($"Error: {result.StandardError}"); // Async execution with await var asyncResult = await Command.Run("dotnet", "--version").Task; Console.WriteLine(asyncResult.StandardOutput); // e.g., "7.0.100" // Command with multiple arguments Command.Run("git", "commit", "-m", "critical bugfix").Wait(); ``` -------------------------------- ### Configure and execute commands with Shell Source: https://github.com/madelson/medallionshell/blob/master/README.md Use a Shell object to define reusable command options, with the ability to override or extend them during individual command execution. ```C# private static readonly Shell MyShell = new Shell(options => options.ThrowOnError().Timeout(...)...); ... var command = MyShell.Run("foo.exe", new[] { "arg1", ... }, options => /* can still override/specify further options */); ``` -------------------------------- ### Manage Process Lifecycle with Signals and Timeouts Source: https://context7.com/madelson/medallionshell/llms.txt Use Kill, TrySignalAsync, and options like Timeout or CancellationToken to manage long-running processes. ```csharp using Medallion.Shell; var command = Command.Run("long-running-process"); // Kill the process immediately command.Kill(); // Send CTRL+C signal (cross-platform: SIGINT on Unix, CTRL_C_EVENT on Windows) bool signalSent = await command.TrySignalAsync(CommandSignal.ControlC); if (signalSent) { Console.WriteLine("Signal sent successfully"); } // Send OS-specific signal (Unix example: SIGTERM = 15) var sigterm = CommandSignal.FromSystemValue(15); await command.TrySignalAsync(sigterm); // Timeout with automatic kill var timedCommand = Command.Run("slow-task", options: options => options.Timeout(TimeSpan.FromSeconds(10))); try { await timedCommand.Task; } catch (TimeoutException) { Console.WriteLine("Command timed out and was killed"); } // Cancellation token with kill var cts = new CancellationTokenSource(); var cancellableCommand = Command.Run("interruptible-task", options: options => options.CancellationToken(cts.Token)); // Later, cancel the command cts.Cancel(); try { await cancellableCommand.Task; } catch (OperationCanceledException) { Console.WriteLine("Command was cancelled"); } ``` -------------------------------- ### Execute Asynchronous Piping Source: https://context7.com/madelson/medallionshell/llms.txt Use async methods on StandardInput and StandardOutput to pipe data without blocking the calling thread. ```csharp using Medallion.Shell; var command = Command.Run("my-app"); // Pipe file to standard input asynchronously await command.StandardInput.PipeFromAsync(new FileInfo("input.csv")); // Pipe stream to standard input using var stream = new MemoryStream(Encoding.UTF8.GetBytes("data")); await command.StandardInput.PipeFromAsync(stream, leaveWriterOpen: false, leaveStreamOpen: true); // Pipe lines to standard input var lines = new[] { "first", "second", "third" }; await command.StandardInput.PipeFromAsync(lines); // Pipe from TextReader using var reader = new StringReader("text content"); await command.StandardInput.PipeFromAsync(reader); // Pipe standard output to file await command.StandardOutput.PipeToAsync(new FileInfo("output.txt")); // Pipe standard output to stream using var outputStream = new MemoryStream(); await command.StandardOutput.PipeToAsync(outputStream, leaveReaderOpen: false, leaveStreamOpen: true); // Pipe standard output to collection var outputLines = new List(); await command.StandardOutput.PipeToAsync(outputLines); // Pipe standard output to TextWriter using var writer = new StreamWriter("output.txt"); await command.StandardOutput.PipeToAsync(writer, leaveReaderOpen: false, leaveWriterOpen: true); // Pipe characters to collection var chars = new List(); await command.StandardOutput.PipeToAsync(chars); ``` -------------------------------- ### Attach to Existing Processes Source: https://context7.com/madelson/medallionshell/llms.txt Attach to running processes using their PID or via a Shell instance. ```csharp using Medallion.Shell; int processId = 12345; // Known process ID // Try to attach to an existing process if (Command.TryAttachToProcess(processId, out var attachedCommand)) { Console.WriteLine($"Attached to process {attachedCommand.ProcessId}"); // Wait for the process to exit var result = await attachedCommand.Task; Console.WriteLine($"Process exited with code: {result.ExitCode}"); } else { Console.WriteLine("Failed to attach - process may have exited"); } // Attach with options if (Command.TryAttachToProcess(processId, options => options.ThrowOnError().Timeout(TimeSpan.FromMinutes(5)), out var configuredCommand)) { await configuredCommand.Task; } // Attach via shell instance var shell = new Shell(options => options.ThrowOnError()); if (shell.TryAttachToProcess(processId, out var shellCommand)) { await shellCommand.Task; } ``` -------------------------------- ### Configure Stream Buffering and Input Flushing Source: https://context7.com/madelson/medallionshell/llms.txt Use these methods to manage memory usage by discarding output or to control process blocking by stopping buffering. Manual flushing is required when AutoFlush is disabled for StandardInput. ```csharp using Medallion.Shell; var command = Command.Run("data-producer"); // Discard all output (prevents blocking, saves memory) command.StandardOutput.Discard(); command.StandardError.Discard(); // Stop buffering (allows process to block waiting for reads) command.StandardOutput.StopBuffering(); // Access the underlying stream Stream rawOutput = command.StandardOutput.BaseStream; Encoding encoding = command.StandardOutput.Encoding; // AutoFlush is enabled by default for StandardInput command.StandardInput.AutoFlush = false; // Disable for batch writes command.StandardInput.Write("data1"); command.StandardInput.Write("data2"); command.StandardInput.Flush(); // Manual flush command.StandardInput.AutoFlush = true; // Re-enable ``` -------------------------------- ### Run a Git Commit Command Source: https://github.com/madelson/medallionshell/blob/master/NugetDocumentation.md Use MedallionShell to execute a command-line process with arguments. The .Wait() method ensures the process completes before proceeding. ```C# Command.Run("git", "commit", "-m", "critical bugfix").Wait(); ``` -------------------------------- ### Perform Piping and Redirection in MedallionShell Source: https://context7.com/madelson/medallionshell/llms.txt Use fluent methods or operators to pipe commands and redirect input/output to files, streams, or collections. ```csharp using Medallion.Shell; // Pipe output from one command to input of another var pipedCommand = Command.Run("cat", "input.txt") .PipeTo(Command.Run("grep", "pattern")); await pipedCommand.Task; // Using the pipe operator (|) var result = await (Command.Run("echo", "hello world") | Command.Run("wc", "-c")).Task; // Redirect from file await Command.Run("sort") .RedirectFrom(new FileInfo("unsorted.txt")) .RedirectTo(new FileInfo("sorted.txt")); // Using redirection operators (< and >) await (Command.Run("sort") < new FileInfo("unsorted.txt") > new FileInfo("sorted.txt")); // Redirect to/from streams using var inputStream = new MemoryStream(Encoding.UTF8.GetBytes("input data")); using var outputStream = new MemoryStream(); await Command.Run("cat") .RedirectFrom(inputStream) .RedirectTo(outputStream); // Redirect to collections var outputLines = new List(); await Command.Run("ls", "-la").RedirectTo(outputLines); foreach (var line in outputLines) { Console.WriteLine(line); } // Redirect from collections (writes each item as a line) var inputLines = new[] { "line1", "line2", "line3" }; await Command.Run("cat").RedirectFrom(inputLines); // Redirect to TextWriter using var stringWriter = new StringWriter(); await Command.Run("echo", "hello").RedirectTo(stringWriter); // Chain multiple commands with file I/O (like: step1 < input.txt | step2 > output.txt) await Command.Run("processingStep1") .RedirectFrom(new FileInfo("input.txt")) .PipeTo(Command.Run("processingStep2")) .RedirectTo(new FileInfo("output.txt")); // Redirect standard error separately await Command.Run("my-app") .RedirectTo(new FileInfo("stdout.log")) .RedirectStandardErrorTo(new FileInfo("stderr.log")); ``` -------------------------------- ### Piping Streams to Sinks and Sources Source: https://github.com/madelson/medallionshell/blob/master/README.md Pipes data between standard IO streams and external sources like files or collections. ```C# command.StandardInput.PipeFromAsync(new FileInfo("input.csv")); // pipes in all bytes from input.csv var outputLines = new List(); command.StandardOutput.PipeToAsync(outputLines); // pipe output text to a collection ``` -------------------------------- ### Chaining Commands with Piping Source: https://github.com/madelson/medallionshell/blob/master/README.md Chains commands using explicit piping methods or command-line style operators. ```C# await Command.Run("processingStep1.exe") .RedirectFrom(new FileInfo("input.txt")) .PipeTo(Command.Run("processingStep2.exe")) .RedirectTo(new FileInfo("output.txt")); // alternatively, this can be expressed with operators as on the command line await Command.Run("ProcssingStep1.exe") < new FileInfo("input.txt") | Command.Run("processingStep2.exe") > new FileInfo("output.text"); ``` -------------------------------- ### Access Process Properties Source: https://context7.com/madelson/medallionshell/llms.txt Retrieve process IDs and underlying System.Diagnostics.Process objects. ```csharp using Medallion.Shell; // ProcessId is always available var command = Command.Run("my-app"); Console.WriteLine($"Process ID: {command.ProcessId}"); // For piped commands, get all process IDs var pipedCommand = Command.Run("cat", "file.txt") | Command.Run("grep", "pattern"); foreach (int pid in pipedCommand.ProcessIds) { Console.WriteLine($"PID in chain: {pid}"); } // Access underlying Process object (requires DisposeOnExit(false)) var cmdWithProcess = Command.Run("notepad", options: options => options.DisposeOnExit(false)); Process process = cmdWithProcess.Process; Console.WriteLine($"Process Name: {process.ProcessName}"); // Access all processes in a piped command foreach (Process p in cmdWithProcess.Processes) { Console.WriteLine($"Process: {p.Id}"); } // Always dispose when using DisposeOnExit(false) ((IDisposable)cmdWithProcess).Dispose(); ``` -------------------------------- ### Accessing Standard IO Results Source: https://github.com/madelson/medallionshell/blob/master/README.md Captures standard output and error from a command result after execution. ```C# var command = Command.Run(...); var result = await command.Task; Console.WriteLine($"{result.StandardOutput}, {result.StandardError}"); ``` -------------------------------- ### Handle Command Errors Source: https://context7.com/madelson/medallionshell/llms.txt Manage failures through result inspection or exception handling. ```csharp using Medallion.Shell; // Check result manually var command = Command.Run("git", "status"); var result = command.Result; if (!result.Success) { Console.WriteLine($"Command failed with exit code: {result.ExitCode}"); Console.WriteLine($"Error output: {result.StandardError}"); } // Throw on non-zero exit code try { Command.Run("invalid-command", options: options => options.ThrowOnError()).Wait(); } catch (ErrorExitCodeException ex) { Console.WriteLine($"Command failed with exit code: {ex.ExitCode}"); Console.WriteLine($"Message: {ex.Message}"); } // Handle timeout try { await Command.Run("sleep", "60", options: options => options.Timeout(TimeSpan.FromSeconds(5))).Task; } catch (TimeoutException) { Console.WriteLine("Command timed out"); } // Handle cancellation var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(2)); try { await Command.Run("sleep", "60", options: options => options.CancellationToken(cts.Token)).Task; } catch (TaskCanceledException) { Console.WriteLine("Command was cancelled"); } ``` -------------------------------- ### Merge Standard Output and Error Source: https://context7.com/madelson/medallionshell/llms.txt Use GetOutputAndErrorLines to interleave standard output and error streams into a single sequence of lines. ```csharp using Medallion.Shell; var command = Command.Run("my-app", "--verbose"); // Get merged output and error lines (like 2>&1 on command line) foreach (var line in command.GetOutputAndErrorLines()) { Console.WriteLine(line); } // Lines from stdout and stderr are interleaved as they arrive // but individual lines are never broken up ``` -------------------------------- ### Direct Stream Interaction Source: https://github.com/madelson/medallionshell/blob/master/README.md Interacts with standard input, output, and error streams using TextReader/TextWriter or raw byte streams. ```C# var command = Command.Run(...); command.StandardInput.Write("some text"); // e.g. write as text command.StandardInput.BaseStream.Write(new byte[100]); // e.g. write as bytes command.StandardOutput.ReadLine(); // e.g. read as text command.StandardError.BaseStream.Read(new byte[100]); // e.g. read as bytes ``` -------------------------------- ### Consuming Merged Output Streams Source: https://github.com/madelson/medallionshell/blob/master/README.md Reads stdout and stderr as a single merged stream of lines. ```C# var command = Command.Run(...); foreach (var line in command.GetOutputAndErrorLines()) { Console.WriteLine(line); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.