我可以理解,关于这个主题有很多问题,但他们都不能真正解决我的问题。所以我在这里提出了我的代码,我希望在这里指出我的错误。C#和Python之间的进程间通信
我有一个用C#编写的程序,它将调用一个python可执行文件/文件。第一个要求是我通过输入流传递一个参数给python文件。这我可以做。我现在面临的真正问题是,我必须查看我的python文件是否正在打印“请输入argument_x”,我必须在我的C#代码中读取此输出,并检查它是否为argument_x,然后仅将参数值写入输入流。以下是C#和Python的代码片段。
的C#代码如下:
using System;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
//Create a new process object
Process myProcess = new Process();
//Provide the start information for the process
myProcess.StartInfo.FileName = "python.exe";
myProcess.StartInfo.Arguments = "mytestpython.py";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.RedirectStandardOutput = true;
StreamReader myStreamReader;
StreamWriter myStreamWriter;
//Invoke the process from current process
myProcess.Start();
myStreamReader = myProcess.StandardOutput;
//Read the standard output of the spawned process.
string myString = myProcess.StandardOutput.ReadToEnd();
Console.WriteLine(myString);
if (myString.Contains("argument_x"))
{
myStreamWriter = myProcess.StandardInput;
String argument = "argument_value";
myStreamWriter.WriteLine(argument);
}
myProcess.WaitForExit();
myStreamWriter.Close();
myStreamReader.Close();
myProcess.Close();
}
}
}
在mytestpython.py文件Python程序是这样的:
import sys
import getpass
prompt_string = "Please enter argument_x"
if sys.stdin.isatty():
reqd_arg = getpass.getpass(prompt=prompt_string)
else:
print(prompt_string)
reqd_arg = sys.stdin.readline().rstrip()
请帮我,因为我觉得我已经正确编写了90%的代码,并在两者之间发生了一些小错误。在此先感谢您的帮助。
确保您在每次输出后刷新或无法正常工作。 – Dani
@Dani你能告诉我使用哪个函数吗? Autoflush什么的?究竟在哪里? –
'myStreamWriter.WriteLine'把'myStreamWriter.Flush(');' – Dani