Skip to content

Repository files navigation

GitHub Actions

ProcessX

ProcessX simplifies call an external process with the aync streams in C# 8.0 without complex Process code. You can receive standard output results by await foreach, it is completely asynchronous and realtime.

image

Also provides zx mode to write shell script in C#, details see Zx section.

image

Table of Contents

Getting Started

Install library from NuGet that support from .NET Standard 2.0.

PM> Install-Package ProcessX

Main API is only Cysharp.Diagnostics.ProcessX.StartAsync and throws ProcessErrorException when error detected.

  • Simple, only write single string command like the shell script.
  • Asynchronous, by C# 8.0 async streams.
  • Manage Error, handling exitcode and stderror.
usingCysharp.Diagnostics;// using namespace// async iterate.awaitforeach(stringiteminProcessX.StartAsync("dotnet --info")){Console.WriteLine(item);}// receive string result from stdout.varversion=awaitProcessX.StartAsync("dotnet --version").FirstAsync();// receive buffered result(similar as WaitForExit).string[]result=awaitProcessX.StartAsync("dotnet --info").ToTask();// like the shell exec, write all data to console.awaitProcessX.StartAsync("dotnet --info").WriteLineAllAsync();// consume all result and wait complete asynchronously(useful to use no result process).awaitProcessX.StartAsync("cmd /c mkdir foo").WaitAsync();// when ExitCode is not 0 or StandardError is exists, throws ProcessErrorExceptiontry{awaitforeach(variteminProcessX.StartAsync("dotnet --foo --bar")){}}catch(ProcessErrorExceptionex){// int .ExitCode// string[] .ErrorOutputConsole.WriteLine(ex.ToString());}

Cancellation

to Cancel, you can use WithCancellation of IAsyncEnumerable.

// when cancel has been called and process still exists, call process kill before exit.awaitforeach(variteminProcessX.StartAsync("dotnet --info").WithCancellation(cancellationToken)){Console.WriteLine(item);}

timeout, you can use CancellationTokenSource(delay).

using(varcts=newCancellationTokenSource(TimeSpan.FromSeconds(1))){awaitforeach(variteminProcessX.StartAsync("dotnet --info").WithCancellation(cts.Token)){Console.WriteLine(item);}}

Raw Process/StdError Stream

In default, when stdError is used, buffering error messages and throws ProcessErrorException with error messages after process exited. If you want to use stdError in streaming or avoid throws error when process using stderror as progress, diagnostics, you can use GetDualAsyncEnumerable method. Also GetDualAsyncEnumerable can get raw Process, you can use ProcessID, StandardInput etc.

// first argument is Process, if you want to know ProcessID, use StandardInput, use it.var(_,stdOut,stdError)=ProcessX.GetDualAsyncEnumerable("dotnet --foo --bar");varconsumeStdOut=Task.Run(async()=>{awaitforeach(variteminstdOut){Console.WriteLine("STDOUT: "+item);}});varerrorBuffered=newList<string>();varconsumeStdError=Task.Run(async()=>{awaitforeach(variteminstdError){Console.WriteLine("STDERROR: "+item);errorBuffered.Add(item);}});try{awaitTask.WhenAll(consumeStdOut,consumeStdError);}catch(ProcessErrorExceptionex){// stdout iterator throws exception when exitcode is not 0.Console.WriteLine("ERROR, ExitCode: "+ex.ExitCode);// ex.ErrorOutput is empty, if you want to use it, buffer yourself.// Console.WriteLine(string.Join(Environment.NewLine, errorBuffered));}

Read Binary Data

If stdout is binary data, you can use StartReadBinaryAsync to read byte[].

byte[]bin=awaitProcessX.StartReadBinaryAsync($"...");

Change acceptable exit codes

In default, ExitCode is not 0 throws ProcessErrorException. You can change acceptable exit codes globally by ProcessX.AcceptableExitCodes property. Default is [0].

Zx

like the google/zx, you can write shell script in C#.

// ProcessX and C# 9.0 Top level statement; like google/zx.usingZx;usingstaticZx.Env;// `await string` execute process like shellawait"cat package.json | grep name";// receive result msg of stdoutvarbranch=await"git branch --show-current";await$"dep deploy --branch={branch}";// parallel request (similar as Task.WhenAll)awaitnew[]{"echo 1","echo 2","echo 3",};// you can also use cd(chdir)await"cd ../../";// run with $"" automatically escaped and quotedvardir="foo/foo bar";awaitrun($"mkdir {dir}");// mkdir "/foo/foo bar"// helper for Console.WriteLine and colorizelog("red log.",ConsoleColor.Red);using(color(ConsoleColor.Blue)){log("blue log");Console.WriteLine("also blue");awaitrun($"echo {"blue blue blue"}");}// helper for web requestvartext=awaitfetchText("http://wttr.in");log(text);// helper for ReadLine(stdin)varbear=awaitquestion("What kind of bear is best?");log($"You answered: {bear}");// run has some variant(run2, runl, withTimeout, withCancellation)// runl returns string[](runlist -> runl)varsdks=awaitrunl($"dotnet --list-sdks");

writing shell script in C# has advantage over bash/cmd/PowerShell

  • Static typed
  • async/await
  • Code formatter
  • Clean syntax via C#
  • Powerful editor environment(Visual Studio/Code/Rider)

Zx.Env has configure property and utility methods, we recommend to use via using static Zx.Env;.

usingZx;usingstaticZx.Env;// Env.verbose, write all stdout/stderror log to console. default is true.verbose=false;// Env.useShell, default is true; which invoke process by `cmd/bash "command argment..."`.useShell=true;// Env.shell, default is Windows -> "cmd /c", Linux -> "(which bash) -c";.shell="/bin/sh -c";// Env.terminateToken, CancellationToken that triggered by SIGTERM(Ctrl + C).vartoken=terminateToken;// Env.fetch(string requestUri), request HTTP/1, return is HttpResponseMessage.varresp=awaitfetch("http://wttr.in");if(resp.IsSuccessStatusCode){Console.WriteLine(awaitresp.Content.ReadAsStringAsync());}// Env.fetchText(string requestUri), request HTTP/1, return is string.vartext=awaitfetchText("http://wttr.in");Console.WriteLine(text);// Env.sleep(int seconds|TimeSpan timeSpan), wrapper of Task.Delay.awaitsleep(5);// wait 5 seconds// Env.withTimeout(string command, int seconds|TimeSpan timeSpan), execute process with timeout. Require to use with "$".awaitwithTimeout($"echo foo",10);// Env.withCancellation(string command, CancellationToken cancellationToken), execute process with cancellation. Require to use with "$".awaitwithCancellation($"echo foo",terminateToken);// Env.run(FormattableString), automatically escaped and quoted. argument string requires to use with "$"awaitrun($"mkdir {dir}");// Env.run(FormattableString), automatically escaped and quoted. argument string requires to use with "$"awaitrun($"mkdir {dir}");// Env.runl(FormattableString), returns string[], automatically escaped and quoted. argument string requires to use with "$"varl1=runl("dotnet --list-sdks");// Env.process(string command), same as `await string` but returns Task<string>.vart=process("dotnet info");// Env.processl(string command), returns Task<string[]>.varl2=processl("dotnet --list-sdks");// Env.ignore(Task), ignore ProcessErrorExceptionawaitignore(run($"dotnet noinfo"));// ***2 receives tuple of result (StdOut, StdError).var(stdout,stderror)=run2($"");var(stdout,stderror)=runl2($"");var(stdout,stderror)=withTimeout2($"");var(stdout,stderror)=withCancellation2($"");var(stdout,stderror)=process2($"");var(stdout,stderror)=processl2($"");

By default (useShell == true), commands are executed through the shell. This means that dotnet --version is actually converted to something like "cmd /c \"dotnet --version\"" during execution. When strings contain spaces, they need to be escaped, but please note that escape handling differs depending on the shell (cmd, bash, pwsh, etc.). If you want to avoid execution through the shell, you can set Env.useShell = false, which will result in more intuitive execution.

usingZx;usingstaticZx.Env;useShell=false;await"dotnet --version";

If you want to escape the arguments, you can also use run($"string").

If you want to more colorize like Chalk on JavaScript, Cysharp/Kokuban styler for .NET ConsoleApp will help.

Reference

ProcessX.StartAsync overloads, you can set workingDirectory, environmentVariable, encoding.

// return ProcessAsyncEnumerableStartAsync(stringcommand,string?workingDirectory=null,IDictionary<string,string>?environmentVariable=null,Encoding?encoding=null)StartAsync(stringfileName,string?arguments,string?workingDirectory=null,IDictionary<string,string>?environmentVariable=null,Encoding?encoding=null)StartAsync(ProcessStartInfoprocessStartInfo)// return (Process, ProcessAsyncEnumerable, ProcessAsyncEnumerable)GetDualAsyncEnumerable(stringcommand,string?workingDirectory=null,IDictionary<string,string>?environmentVariable=null,Encoding?encoding=null)GetDualAsyncEnumerable(stringfileName,string?arguments,string?workingDirectory=null,IDictionary<string,string>?environmentVariable=null,Encoding?encoding=null)GetDualAsyncEnumerable(ProcessStartInfoprocessStartInfo)// return Task<byte[]>StartReadBinaryAsync(stringcommand,string?workingDirectory=null,IDictionary<string,string>?environmentVariable=null,Encoding?encoding=null)StartReadBinaryAsync(stringfileName,string?arguments,string?workingDirectory=null,IDictionary<string,string>?environmentVariable=null,Encoding?encoding=null)StartReadBinaryAsync(ProcessStartInfoprocessStartInfo)// return Task<string> ;get the first result(if empty, throws exception) and wait completedFirstAsync(CancellationTokencancellationToken=default)// return Task<string?> ;get the first result(if empty, returns null) and wait completedFirstOrDefaultAsync(CancellationTokencancellationToken=default)// return TaskWaitAsync(CancellationTokencancellationToken=default)// return Task<string[]>ToTask(CancellationTokencancellationToken=default)// return TaskWriteLineAllAsync(CancellationTokencancellationToken=default)

Competitor

License

This library is under the MIT License.

About

Simplify call an external process with the async streams in C# 8.0.

Resources

Stars

545 stars

Watchers

18 watching

Forks

Releases

Packages

Used by

Contributors

Languages