c调用python获取返回值_如何从C#中获取python脚本的返回值

1586010002-jmsa.png

Dear ALL:

I am using .NET3.5 C# run a python script and try to get the return value from python

I put the python script under disk C://.

Then in C# run the python script with:ProcessStartInfo Info = new ProcessStartInfo();

Info.FileName = "getvalue.py";

Info.WorkingDirectory = @"c:";

Process Star = Process.Start(Info);

Then how could I get the value from python script.

For example python script return a value "3".

Any tips welcomed and appreciated.

Regards

Kay

解决方案There are two ways of doing it.

First one is very limited and based on exit code. On Windows and Unix-like systems, all applications return integer code which defaults to 0. Traditionally, 0 means "everything is OK", but it could be anything. With Python, exit code is returned by assigning an integer value to the special variable

?. Please see:

http://stackoverflow.com/questions/285289/exit-codes-in-python[^].

On the side of your .NET parent process, when the child process is terminated, you can pick up the exit code using the property System.Diagnostics.Process.ExitCode:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exitcode.aspx[^].

You can synchronize a thread of your parent process with the termination of your child process using the methods System.Diagnostics.Process.WaitForExit:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx[^].

Please note that these methods are blocking, so they are not suitable for calling, say, from a UI thread — you might need to execute all your code using System.Diagnostics.Process from a separate thread, at least in the case if your Python script takes considerable time to complete.

The second approach is more universal but a bit more awkward and is based on console output. You can echo some output text to the console in your Python script. Your parent process needs to pick up this text, parse and process it the way you need. To do that, you need to redirect output from the child process (Python script, in this case) to a stream and read the content of this stream. This is done by redirection of StandardOutput, and, just in case, StandardError streams. Please see:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx[^],

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standarderror.aspx[^].

Both MSDN help pages referenced above show how to do the redirection on the code samples. Please see — they are descriptive enough.

—SA

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值