开发者

Getting information from scripts/command line calls in C#

开发者 https://www.devze.com 2022-12-22 21:57 出处:网络
I\'ve been writing a couple of apps which use C# as the Gui, but under the hood do all the work via scripts (which may be Python, Ruby etc.).

I've been writing a couple of apps which use C# as the Gui, but under the hood do all the work via scripts (which may be Python, Ruby etc.).

To pass information from the script back to the GUI (for example error reporting etc.) I've usually resorted to calling the script via Process and either

  • Redirected the input (StartInfo.RedirectStandardOutput etc) and read that
  • Created temporary files whic开发者_运维技巧h the GUI monitors/reads to find out what it needs to know

Neither of these methods seems ideal (the second is simply awful imo) but I don't see any other way to do it. Maybe there isn't but I thought it worth asking before I started another app with a similar set of problem.

Thanks


Using ProcessStartInfo.RedirectStandardInput, ProcessStartInfo.RedirectStandardOutput and ProcessStartInfo.RedirectStandardError (as well as Process.ExitCode) is perfectly fine, especially when your scripts rigorously follow a certain convention:

  • warnings and error descriptions go to stderr
  • in case of errors exit with a non-zero exit code (avoid the special value 259 STILL_ACTIVE)
  • in case of errors exit early if it makes sense to do so (avoids having the user sift through kilometric error messages, or your GUI having to accomodate kilometric error messages in e.g. a MessageBox)
  • all other, regular output goes to stdout (if applicable)

Your UI can then easily:

  • read script stdout and stderr into separate buffers until script terminates
  • check script exit code:
    • if exit code is 0 and stderr is empty, inform the user that Operation completed successfully
    • if exit code is 0 and stderr is non-empty, inform the user that Operation completed with warnings, allowing the user to optionally inspect the warnings from the stderr buffer
    • if exit code is non-0, inform the user that Operation has failed with errors, allowing the user to inspect the errors from the stderr buffer
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号