2012-07-23 32 views
3

我希望在我的C#控制台应用程序中嵌入一个exe文件(特别是Python 2.7的解释器中的“python.exe”),这意味着我希望用户输入命令,将解释器的输出接收到字符串变量并使用Console。 WriteLine打印输出。到目前为止我的代码是:在C#控制台中嵌入一个exe文件?

ProcessStartInfo processStartInfo = new ProcessStartInfo("C:/Python27/python.exe"); 
processStartInfo.RedirectStandardInput = true; 
processStartInfo.RedirectStandardOutput = true; 
processStartInfo.UseShellExecute = false; 

Process process = Process.Start(processStartInfo); 

if (process != null) 
{ 
    while (true) 
    { 
     process.StandardInput.WriteLine(Console.ReadLine()); 
     process.StandardInput.Close(); 

     string output = process.StandardOutput.ReadToEnd(); 
     Console.WriteLine(output); 
    } 
} 

我可以写“打印5”,并得到正确的输出,但再次书写时,我收到以下错误:

Cannot write to a closed TextWriter.

我认为这个错误是因为我关闭了StandardInput,但没有这行代码,我根本没有得到任何输出。我可以使用什么发送多个命令到exe文件?

预先感谢您!

+1

你可以调用process.StandardInput.Flush()而不是Close()吗? – scottm 2012-07-23 20:13:25

+2

你有没有考虑过使用IronPython? – 2012-07-23 20:13:35

+1

调用这个“嵌入”非常非正统。 :) – bzlm 2012-07-23 20:42:15

回答

1

改为拨打process.StandardInput.Flush()。 Flush使任何缓冲的TextWriter将其所有输入写入目标,这就是发生了什么 - 您调用了Close(),它具有刷新缓冲区以及关闭流的副作用。

有关更多信息,请参阅the MSDN documentation

+0

嘿,谢谢你的回复,我是发布这个问题的人(在我朋友家里)。替换'Close()'到'Flush()'不起作用,它甚至不运行我放的第一个命令... – 2012-07-23 20:40:11

+0

在StreamReader.ReadToEnd()上发现此评论 - “ReadToEnd假定流知道当它结束时对于交互式协议,服务器只在你询问并且没有关闭连接时发送数据,ReadToEnd可能会无限期地阻塞,因为它没有达到目的,应该避免。“看来在StreamReader上使用.EndOfStream属性也会导致无限块。那么问题是,你为什么要这样做?您可能需要重新考虑您的方法。 Mark Byers对Iron Python有一个很好的建议。 – Kilanash 2012-07-23 21:59:52

+0

正如我在这个问题的评论中提到的,我尝试过使用IronPython。问题是我正在使用几个库作为.PYD文件,因此只能与CPython一起使用。 – 2012-07-26 16:51:46

相关问题