作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我已经在 C# 中使用 Python 进行了试验,但我不知道如何执行 Python 脚本并编写命令/数据。我一直在寻找这个链接:“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”会起作用,但我不会写...
最佳答案
您需要 C# 程序和 python 程序同时工作吗?如果不是,您可以从 C# 程序收集所有数据并将它们作为命令行参数或两个程序共享的文件发送到 python 脚本。
要在 python 脚本中使用参数,您可以使用 argparse module .
关于c# - 如何从 C# 向 Python 脚本发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39165595/
我是一名优秀的程序员,十分优秀!