我正在尝试使用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.exe
,因此您可以直接运行它。你不需要cmd.exe
。这只会让事情变得更复杂李>StandardError
,但版本信息不是写入到那里的。改为重定向StandardOutput
李>%PATH%
环境变量中时,整个方法才会起作用。如果安装时没有安装,将找不到Python李>和3。请记住,适用于我的代码:
输出:
相关问题 更多 >
编程相关推荐