我在这个过程中实现了异步读/写操作的功能。但是,不会执行提供给进程的命令。
创建一个进程并重定向必要的线程:
StringBuilder outputText = new StringBuilder();
StringBuilder outputError = new StringBuilder();
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true,
UseShellExecute = false,
ErrorDialog = false,
Arguments = "/cpython.exe"
};
process.StartInfo = startInfo;
AutoResetEvent outputWaitHandle = new AutoResetEvent(false);
AutoResetEvent errorWaitHandle = new AutoResetEvent(false);
process.OutputDataReceived += (sender, e) =>
{
if (e.Data == null) { outputWaitHandle.Set();}
else{ outputText.AppendLine(e.Data); }
}
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null) { errorWaitHandle.Set();}
else{ outputError.AppendLine(e.Data); }
}
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
if (timeout > 0)
{
if (process.WaitForExit(timeout) &&
outputWaitHandle(timeout) &&
errorWaitHandle.WaitOne(timeout))
{
// Do some work...
}
}
异步写入流:
if (process.StandardInput.BaseStream.CanWrite)
{
byte[] bytesToWrite = Encoding.ASCII.GetBytes("print 'Hello'");
IAsyncResult handle = process.StandardInput.BaseStream.BeginWrite(bytesToWrite, 0, bytesToWrite.Length, EndWriteCallBack, process.StandardInput.BaseStream);
if (handle.IsCompleted)
{
// Do smth ....
}
else
{
handle.AsyncWaitHandle.WaitOne();
}
}
//Callback func
void EndWriteCallBack(IAsyncResult handle)
{
process.StandardInput.BaseStream.EndWrite(handle);
}
在输出中,我希望我的异步输出将打印的字符串返回给我:
outputText = "print 'Hello'"
就像控制台一样。但是,输出始终为空。告诉我可能是什么问题?
PS:如果你删除输入流的重定向,一切正常。但我希望能够将多个命令发送到同一个控制台,因为这可以通过直接使用它来完成。
在这里找到了我的问题的答案(感谢作者,++++ to karma!):
Asynchronous I/O to the console, a fully interactive program
稍微更正了代码(添加了一个实现委托+注释的方法),我得到了这个:
测试程序:
注意,问题!
将“python.exe”作为命令传递仍然不会返回输出。但是,如果您故意发送无效命令,则将返回 python 返回的错误。
问题! 你如何获得所有的 Python 输出???
PS:链接到运行 cmd.exe 的参数:
CMD - 启动 windows 命令解释器的新副本