我一直在从C#尝试Python,但不知道如何执行Python脚本并编写它的命令/数据。我一直在查看这个链接:https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee,但只展示了如何读取Python脚本的输出,而没有展示如何在打开/执行脚本时编写内容。
例如,我想从C#打开一个Python脚本,并将一些数据发送给其中的raw_input()函数。
你能帮我吗?链接、例子,都可以...现在我很迷茫。
PS:我不想使用IronPython。
C#示例:
private void button1_Click(object sender, EventArgs e)
{
string python = @"C:\Python27\python.exe";;
string myPythonApp = "myscript/test01.py";
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);
myProcessStartInfo.UseShellExecute = false
myProcessStartInfo.CreateNoWindow = true
myProcessStartInfo.RedirectStandardOutput = true
myProcessStartInfo.RedirectStandardInput = true;
myProcessStartInfo.Arguments = myPythonApp;
//<>//---------------ISSUE?--------------------------------
Process myProcessW = new Process();
Process myProcessR = new Process();//
myProcessW.StartInfo = myProcessStartInfo;
myProcessR.StartInfo = myProcessStartInfo;
myProcessW.Start();
myProcessR.Start();
StreamWriter myStreamWriter = myProcessW.StandardInput;
string inputText;
inputText = textBox1.Text;
myStreamWriter.WriteLine(inputText); // <--OK!
myProcessW.WaitForExit();
myProcessW.Close();
//
StreamReader myStreamReader = myProcessR.StandardOutput;
MessageBox.Show("01"); //For Debug, is executed
string myString = myStreamReader.ReadLine();
MessageBox.Show("02"); //For Debug, is NOT executed
label1.Text = myString;
myProcessR.WaitForExit();
myProcessR.Close();
//<>//---------------/ISSUE?--------------------------------
}
Python示例(myscript/test01.py):
aaa = raw_input("> ")
print "Ok, you say:",aaa
重要更新:我发现如果我设置“myProcessStartInfo.RedirectStandardInput = false”,“RedirectStandardOutput”将会起作用,但我不会写...
myProcessStartInfo.RedirectStandardInput = true;
和StreamWriter myStreamWriter = myProcess.StandardÌnput;
并向流写入器写入吗?在 Python 中,你可以使用raw_input()
从标准输入读取行。 - janbrohlmyProcessR
和myProcessW
必须是同一个进程。 - janbrohl