检查是否安装了 python

Check if python is installed

我正在尝试使用 c#(作为 WinForms 应用程序的一部分)从电脑上获取 python 的已安装版本。 我试图通过在这两个线程 here and here 之后创建一个新的子进程来做到这一点,但是 none 似乎有效...

我尝试将流程构造函数的字段反过来更改为:

UseShellExecute = true
RedirectStandardOutput = false
CreateNoWindow = false

而且 Arguments 似乎甚至没有传递给子进程,因此不会输出任何内容..(它只是定期打开一个 cmd window)

我错过了什么?

这是当前代码

这是一个粗略的初始代码,一旦我收到输出消息就会更改..

*这两种方法似乎都启动了 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;
    }
  1. Python就是python.exe,直接运行就可以了。你不需要 cmd.exe。它只会让事情变得更复杂。
  2. 您重定向 StandardError,但这不是写入版本信息的地方。改为重定向 StandardOutput
  3. 仅当 Python 已添加到 %PATH% 环境变量时,整个方法才有效。如果没有安装它,将找不到 Python。

考虑到 3.,适用于我的代码:

void Main()
{
    var p = new PythonCheck();
    Console.WriteLine(p.Version());
}

class PythonCheck {
    public string Version()
     {
        string result = "";

        ProcessStartInfo pycheck = new ProcessStartInfo();
        pycheck.FileName = @"python.exe";
        pycheck.Arguments = "--version";
        pycheck.UseShellExecute = false;
        pycheck.RedirectStandardOutput = true;
        pycheck.CreateNoWindow = true;

        using (Process process = Process.Start(pycheck))
        {               
            using (StreamReader reader = process.StandardOutput)
            {
                result = reader.ReadToEnd();
                return result;
            }
        }
    }
}

输出:

Python 3.9.7