使用C来输入和输出到Python

2024-09-30 18:34:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用C来读写Python脚本。我可以成功地写入脚本并让它在我的C命令上运行函数。但是我不知道如何在StreamReader中使用RedirectStandardOutput来接收python代码的结果(返回值或write-to-screen语句);它只会锁定程序。在

代码:

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代码:

^{pr2}$

Tags: theto代码命令脚本truenewprocess