检查是否安装了python

2024-09-28 19:33:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用c#(作为WinForms应用程序的一部分)从pc上获取已安装的python版本。 我正试图通过在这两个线程herehere之后创建一个新的子进程来实现这一点,但似乎都不起作用

我已尝试以另一种方式将流程构造函数的字段更改为:

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;
    }

Tags: cmdfalsetruenewshowprocresultprocess
1条回答
网友
1楼 · 发布于 2024-09-28 19:33:30
  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

相关问题 更多 >