gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:37:14 24 4
gpt4 key购买 nike

我已经在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com