如何从C#向Python脚本发送数据

5

我一直在从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() 从标准输入读取行。 - janbrohl
为了交换更复杂的数据,您可以使用JSON(Python标准库支持并且也可用于C#)。 - janbrohl
嗨,我尝试了你说的,但是“StreamReader myStreamReader = myProcessR.StandardOutput;”现在不起作用。请看我的例子... - Edgardo Poea
1
myProcessRmyProcessW必须是同一个进程。 - janbrohl
1个回答

0

您需要让C#程序和Python程序同时工作吗?如果不需要,您可以从C#程序中收集所有数据,并将它们作为命令行参数或文件发送给Python脚本。

要在Python脚本中使用命令行参数,您可以使用argparse模块


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接