从C#net调用python.py
我在从C#调用python脚本时遇到问题。我的python脚本基于param 1和param 2计算一个值,并发送计算出的值。我无法得到计算出的值。比如说,我使用一个简单的python类,并调用C# 下面是python.py:从C#net调用python.py,c#,python,process,C#,Python,Process,我在从C#调用python脚本时遇到问题。我的python脚本基于param 1和param 2计算一个值,并发送计算出的值。我无法得到计算出的值。比如说,我使用一个简单的python类,并调用C# 下面是python.py: import argparse class demo: def add(self,a,b): return a+b def main(a,b): obj=demo() value=obj.add(a,b) print(value) return
import argparse
class demo:
def add(self,a,b):
return a+b
def main(a,b):
obj=demo()
value=obj.add(a,b)
print(value)
return value
if __name__ == "__main__":
arg_parse = argparse.ArgumentParser()
arg_parse.add_argument("a")
arguments = arg_parse.parse_args()
main(arguments.a,3)
下面是调用它的C代码
Process p = new Process();
int a = 2;
p.StartInfo.FileName = "C:\\Users\\xyx\\AppData\\Local\\Programs\\Python\\Python36-32\\pythonw\\python.exe";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.Arguments = "C:\\Users\\xyx\\AppData\\Local\\Programs\\Python\\Python36-32\\pythonw\\python.py "+a; parameter
p.Start();
StreamReader s = p.StandardOutput;
standardError = s.ReadToEnd();
output = s.ReadToEnd().Replace(Environment.NewLine, string.Empty);
p.WaitForExit();
因为在python中2,3被发送到main(),所以我想要返回'5'。我不知道怎么把它拿回来。请帮助以下代码片段适合我:调用Python的C代码
using System;
using System.Diagnostics;
using System.IO;
namespace ScriptInterface
{
public class ScriptRunner
{
//args separated by spaces
public static string RunFromCmd(string rCodeFilePath, string args)
{
string file = rCodeFilePath;
string result = string.Empty;
try
{
var info = new ProcessStartInfo(@"C:\Users\xyz\AppData\Local\Programs\Python\Python37\python.exe");
info.Arguments = rCodeFilePath + " " + args;
info.RedirectStandardInput = false;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
info.CreateNoWindow = true;
using (var proc = new Process())
{
proc.StartInfo = info;
proc.Start();
proc.WaitForExit();
if (proc.ExitCode == 0)
{
result = proc.StandardOutput.ReadToEnd();
}
}
return result;
}
catch (Exception ex)
{
throw new Exception("R Script failed: " + result, ex);
}
}
public static void Main()
{
string args = "1 2";
string res = ScriptRunner.RunFromCmd(@"your file path", args);
}
}
}
下面是Python代码,它接受两个输入并返回这些输入的总和:
import sys
def add_numbers(x,y):
sum = x + y
return sum
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
print(add_numbers(num1, num2))
我得到proc.ExitCode=2而不是0 python代码是否在C代码之外工作?我是说在命令提示符下?问题可能在于python脚本是。否则它会正确执行。我还试着复制粘贴上面的代码。同样的行为。它不会抛出异常。如果(proc.exitcode==0)奇怪,您是否更改了Python.exe的路径??我在我的系统上安装了python37。好吧,我在我的系统上进行了尝试,它按预期工作,但当我在下面的代码ScriptRunner.RunFromCmd(@“C:\Users\xyz\Desktop\test.py”,args)中手动编译源文件的路径时;我有出口代码2。