开发者

Python & C#: Is IronPython absolutely necessary?

开发者 https://www.devze.com 2023-01-17 22:21 出处:网络
I\'m primarily a C# programmer, but have been left with a project that leaves me with 2 options: Call out to a python script (saved as a .py file) and process the return value, OR...

I'm primarily a C# programmer, but have been left with a project that leaves me with 2 options:

  1. Call out to a python script (saved as a .py file) and process the return value, OR...
  2. Rewrite the whole python script (involving 6 .py files in total) in C#.

Naturally, Option 2 is a MAJOR waste of time if I can simply implement Option 1. Moreover, Option 1 is a learning opportunity, while Option 2 is a total geek copout.

So, my question is this: Is there a way to build a C# Process object to trigger the .py file's script AND catch the script's return value without using IronPython? I don't have anything against possibly using IronPython, I just need a solution as soon as possible, so if I can sidestep the I.P. 开发者_开发技巧learning curve until I have less urgent work to do, that would be optimal.

Thanks.


Use Process.Start to run the Python script. In the ProcessStartInfo object, you specify:

  • FileName = the path and file name of the Python script.

  • Arguments = any arguments that you want to pass to the script.

  • RedirectStandardOutput = true (and RedirectStandardError if needed)

  • UseShellExecute = false

Then you get a Process object on which you can do some things, in particular:

  • Use Process.StandardOutput to read the Python script’s output. You could, for example, call ReadToEnd() on this to get a single string containing the entire output, or call ReadLine() in a loop.

  • Use Process.ExitCode to read the return code of the script.

  • Use Process.WaitForExit to wait for the script to finish.


Use System.Diagnostics.Process to run the Python script and then use Process.ExitCode to retrieve the return value of the script once it's done:

// Start the script
var process = System.Diagnostics.Process.Start("python MyScript.py");

// Wait for the script to run
process.WaitForExit();

int returnVal = process.ExitCode;


You can do something like:

Process py = new Process();
py.StartInfo.FileName = "python.exe";
py.StartInfo.Arguments = "c:\\python\\script.py";
py.StartInfo.UseShellExecute = false;
py.StartInfo.CreateNoWindow = true;
py.StartInfo.RedirectStandardOutput = true;
py.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
py.Start();
py.BeginOutputReadLine();
py.WaitForExit();
py.Close();

But, I must say that you can have multiple systems, based in different languages, since they can understand what each one says. I mean, there're some standards that can be thought to glue the whole thing. The python system can feed the C# system with JSON, XML, or some other standard, in a webservice built in Python, for example. Sometimes it's better to review your architecture.

0

精彩评论

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