我在从 C# 调用 python 脚本时遇到问题。我的 python 脚本根据参数 1 和参数 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 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();
由于 2,3 在 python 中被发送到 main(),所以我想要返回“5”。我不知道如何取回它。请帮忙
以下代码片段对我有用:C# code to call Python
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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)