【发布时间】:2017-05-10 02:23:29
【问题描述】:
我正在尝试使用 C# 来读取和写入 Python 脚本。我可以成功写入脚本并让它在我的 C# 命令上运行函数。但我不知道如何将 RedirectStandardOutput 与 StreamReader 一起使用来接收 python 代码的结果(返回值或写入屏幕语句);它只是锁定程序。
C#代码:
Process myPythonSimpleArithmeticProgram = new Process();
ProcessStartInfo thisInfo = new ProcessStartInfo();
thisInfo.FileName = "python";
thisInfo.Arguments = "pythonSimpleArithmetic.py";
thisInfo.RedirectStandardInput = true;
//thisInfo.RedirectStandardOutput = true;
thisInfo.UseShellExecute = false;
myPythonSimpleArithmeticProgram.StartInfo = thisInfo;
myPythonSimpleArithmeticProgram.Start();
StreamWriter pySW = myPythonSimpleArithmeticProgram.StandardInput;
//python program contains functions for add and multiply
//want to use RedirectStandardOutput to have something like:
//int AddResult1 = pyInputSW.WriteLine("pyAdd, 3, 4");
pySW.WriteLine("pyAdd, 3, 4"); //this writes the answer to the python console
pySW.WriteLine("pyMultiply, 3, 4");
pySW.WriteLine("pyAdd, 5, 6");
Python 代码:
import sys
def pyAdd(x,y):
z = x + y
# Print to console (if desired)
print "Using pyAdd, the sum of %f and %f is %f" % (x, y, z)
# Return a value back to the C# program
return z
def pyMultiply(x,y):
z = x * y
# Print to console (if desired)
print "Using pyMultiply, the product of %f and %f is %f" % (x, y, z)
# Return a value back to the C# program
return z
while True:
testVar = raw_input("Enter the function name: ")
splitInput = testVar.split(",")
if splitInput[0] == "pyAdd":
pyAdd(float(splitInput[1]), float(splitInput[2]))
elif splitInput[0] == "pyMultiply":
pyMultiply(float(splitInput[1]), float(splitInput[2]))
else:
print "Function %s not available" % splitInput[0]
【问题讨论】:
-
很久以前的问题了,你最后解决了吗?我也在尝试通过 C# 代码运行 Python.exe。但是 Imports 需要很长时间,因为 Python.exe 每次都会执行。我还想在文件加载后调用具有不同参数的 Python 函数,以避免每次都导入字符。