【发布时间】:2021-11-23 16:40:05
【问题描述】:
我正在尝试使用 c#(作为 WinForms 应用程序的一部分)从 PC 获取已安装的 python 版本。 我试图通过在这两个线程 here 和 here 之后创建一个新的子进程来做到这一点,但似乎没有一个工作......
我已经尝试将流程构造函数的字段改为:
UseShellExecute = true
RedirectStandardOutput = false
CreateNoWindow = false
而且似乎Arguments 甚至没有传递给子进程,所以什么都不会输出..(它只是定期打开一个 cmd 窗口)
我错过了什么?
这是当前代码
这是一个粗略的初始代码,一旦我得到输出消息就会改变..
*这两种方法似乎都启动了 cmd 进程,但它只是卡住并且不输出任何内容,即使没有重定向。
private bool CheckPythonVersion()
{
string result = "";
//according to [1]
ProcessStartInfo pycheck = new ProcessStartInfo();
pycheck.FileName = @"cmd.exe"; // Specify exe name.
pycheck.Arguments = "python --version";
pycheck.UseShellExecute = false;
pycheck.RedirectStandardError = true;
pycheck.CreateNoWindow = true;
using (Process process = Process.Start(pycheck))
{
using (StreamReader reader = process.StandardError)
{
result = reader.ReadToEnd();
MessageBox.Show(result);
}
}
//according to [2]
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "python --version",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
result = proc.StandardOutput.ReadLine();
// do something with result
}
//for debug purposes only
MessageBox.Show(result);
if (!String.IsNullOrWhiteSpace(result))
{
MessageBox.Show(result);
return true;
}
return false;
}
【问题讨论】:
标签: python c# windows winforms cmd