在C#中执行Python函数并返回结果
我有一个Python文件,里面装满了我需要用jsonrpc发布的函数。目前我可以把这些函数发布到指定的网站,并在Python中获取结果。但现在我想从C#运行这个Python脚本,获取结果并对结果进行处理。我在让Python脚本运行并将结果返回给C#时遇到了麻烦。
我更倾向于不下载IronPython,所以如果有不使用它的解决方案就太好了。
现在发生的情况是,当我执行Process.Start(start))
这一行时,会弹出一个命令行窗口,但很快又消失了,然后什么结果都没有返回给调用者。
Python代码:
#!usr/bin/python
import sys
import json
import jsonrpclib
def dc_906(orderid, givexNum, amount):
jsonrpclib.config.use_jsonclass = True
server = jsonrpclib.Server('https://dev-dataconnect.com:50')
ping1 = server.dc_906('en', orderid, 'userid', 'password', num, amount)
print jsonrpclib.history.response #this could be a "return" instead of print, not sure.
if __name__ == "__main__":
function = sys.argv[1]
orderid = sys.argv[2]
num = sys.argv[3]
amount = sys.argv[4]
if function == 'dc_906':
dc_906(orderid, num, amount)
执行这个过程的C#代码(来源于:如何从C#运行Python脚本?)
try
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = @"C:\Python27\python.exe"; //full path to python.exe
//start.FileName = @"C:\Windows\system32\cmd.exe";
//start.Arguments = string.Format("{0} {1} {2} {3}", @"C:\Users\J1035\Documents\Python27\GiveX_python\test.py", "123456789", "603628982592000186162", 20.00);
start.Arguments = string.Format("{0} {1}", @"C:\Users\J1035\Documents\Python27\GiveX_python\test.py", "123456789 603628982592000186162 20.00");
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using(Process process = Process.Start(start))
using (StreamReader reader = process.StandardOutput)
{
string foo = reader.ReadToEnd();
TxtResultOutput.Text += foo;
}
}
catch (Exception ex)
{
var foo = ex.Message;
}
在命令行中运行Python脚本的结果:
1 个回答
4
看起来你在参数那一行忘记写“dc_906”了。没有这个,函数就不会被调用。