【问题标题】:Using C# for input and output to Python使用 C# 对 Python 进行输入和输出
【发布时间】: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 函数,以避免每次都导入字符。

标签: c# python


【解决方案1】:

thisInfo.RedirectStandardOutput = true;

string output = thisInfo.StandardOutput.ReadToEnd();
thisInfo.WaitForExit();
Console.WriteLine("Output:");
Console.WriteLine(output);

Source:

【讨论】:

    猜你喜欢
    • 2013-11-21
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多