我从C#开始尝试使用Python,我不知道如何执行Python脚本并编写It命令/数据。我一直在寻找这个链接:“https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee”
但是只展示了如何阅读Python脚本输出,而不是在脚本打开/执行后如何编写内容。
例如,我想打开一个python脚本(来自C Sharp)并将一些数据从C#发送到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”将起作用,但我不会写...
答案 0 :(得分:0)
你需要C#程序和python同时工作吗? 如果不是,您可以从C#程序收集所有数据,并将它们作为命令行中的参数或两个程序共享的文件发送到python脚本。
要在python脚本中使用参数,您可以使用argparse module。