如何从C#向Python脚本发送数据
发布时间:2020-12-15 21:01:42 所属栏目:百科 来源:网络整理
导读:我已经从C#中试验过 Python,我不知道如何执行Python脚本并编写It命令/数据.我一直在寻找这个链接:“ https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee” 但是只显示如何读取Python脚本输出,而不是在脚本打开/执行后如何
我已经从C#中试验过
Python,我不知道如何执行Python脚本并编写It命令/数据.我一直在寻找这个链接:“
https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee”
但是只显示如何读取Python脚本输出,而不是在脚本打开/执行后如何编写内容. 例如,我想打开一个python脚本(来自C Sharp)并将一些数据从C#发送到raw_input()函数. 你能帮助我吗?链接,例子,都欢迎……我现在迷路了. PS:我不想用铁腕 C#示例: private void button1_Click(object sender,EventArgs e) { string python = @"C:Python27python.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”将起作用,但我不会写… 解决方法
你需要C#程序和python同时工作吗?
如果不是,您可以从C#程序收集所有数据,并将它们作为命令行中的参数或两个程序共享的文件发送到python脚本. 要在python脚本中使用参数,可以使用argparse module. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |