我可以理解,关于这个话题有很多问题,但没有一个能真正解决我的问题。所以我在这里展示了我的代码,我想在这里指出我的错误。在
我有一个用C编写的程序,它将调用python可执行文件。第一个要求是通过输入流将一个参数传递给python文件。我能做到的。如果我的参数是,我现在要检查的是,我的输出是否是,我要检查的是,我的输出是否是。下面是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();
}
}
}
中的python程序mytestpython.py文件如下所示:
^{pr2}$请帮帮我,因为我觉得我已经正确地写了90%的代码,其中有一个小错误。提前谢谢你的帮助。在
当父进程等待子进程完成时,
ReadToEnd()
很有用。在交互式进程通信的情况下,您应该考虑使用BeginOutputReadLine
使用异步通信,请查看MSDN文档here以获取帮助当您执行
myProcess.StandardOutput.ReadToEnd();
操作时,它会尝试读取Python程序的stdout结尾,这意味着它将等待Python程序完成执行并关闭其stdout流,因为它一直在等待C程序的输入。这会导致死锁。在我修改了C代码以接受CLI参数并在提示符下传递密码,如下所示:
}
然后在Python中做一个小的修改:
^{pr2}$瞧,真是太好了!!!在
相关问题 更多 >
编程相关推荐