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

本文关键字:脚本 数据 Python | 更新日期: 2023-09-27 18:04:03

我已经从c#中尝试过Python,我不知道如何执行Python脚本并编写命令/数据。我一直在寻找这个链接:"https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee"

但只展示如何读取Python脚本输出,而不是如何在脚本打开/执行后编写内容。

例如,我想打开一个python脚本(从C夏普),并从c#发送一些数据到raw_input() función。

你能帮我吗?链接,例子,都是欢迎的…我现在迷路了。

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. info ."RedirectStandardOutput = false", "RedirectStandardOutput"将工作,但我不会写…

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

您需要c#程序和python程序同时工作吗?如果没有,您可以从c#程序中收集所有数据,并将它们作为命令行中的参数或两个程序共享的文件发送给python脚本。

要在python脚本中使用参数,可以使用argparse模块。