我正在尝试使用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]
答案 0 :(得分:0)
使用thisInfo.RedirectStandardOutput = true;
string output = thisInfo.StandardOutput.ReadToEnd();
thisInfo.WaitForExit();
Console.WriteLine("Output:");
Console.WriteLine(output);