【发布时间】:2012-07-23 20:10:35
【问题描述】:
我希望在我的 C# 控制台应用程序中嵌入一个 exe 文件(特别是“python.exe”,Python 2.7 的解释器),这意味着我希望用户输入命令,将解释器的输出接收到字符串变量中并使用控制台.WriteLine 打印该输出。到目前为止我的代码是:
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);
}
}
我可以写“print 5”并得到正确的输出,但是当再次写它时,我得到以下错误:
无法写入已关闭的 TextWriter。
我相信这个错误是因为我关闭了 StandardInput,但是如果没有那行代码,我根本不会得到任何输出。我可以使用什么来向 exe 发送多个命令?
提前感谢您!
【问题讨论】:
-
你可以调用 process.StandardInput.Flush() 而不是 Close() 吗?
-
你考虑过使用 IronPython 吗?
-
把这个叫做“嵌入”是很不正统的。 :)
-
我绝对支持 IronPython 的建议。我不认为你可以处理这样的 exe。我一直在玩将 IronPython 嵌入到 c# 4.0 应用程序中。这样做还不错。它只需要很少的代码 - 并不比上面示例中的代码多。
-
我尝试使用 IronPython,但问题是我使用了几个以 .PYD 文件形式提供的库,因此只能与 CPython 一起使用。
标签: c# python console exe embedding