wpf 自动查找python可执行文件的路径

62lalag4  于 2022-12-05  发布在  Python
关注(0)|答案(6)|浏览(198)

我正在做一个项目,使用python作为后台脚本,C#作为guy。我的问题是,我不知道如何使我的GUI自动搜索pythonw.exe文件,以便运行我的python脚本。
目前我使用的路径是:

ProcessStartInfo pythonInfo = new ProcessStartInfo(@"C:\\Users\\Omri\\AppData\\Local\\Programs\\Python\\Python35-32\\pythonw.exe");

但我希望它能自动检测pythonw.exe的路径(我需要提交项目,除非更改代码本身,否则它不会在其他计算机上运行)
任何建议都可能会有帮助。

arknldoa

arknldoa1#

受@ ShashiBhushan答案的启发,我创建了这个函数,用于可靠地获取Python路径;

private static string GetPythonPath(string requiredVersion = "", string maxVersion = "") {
            string[] possiblePythonLocations = new string[3] {
                @"HKLM\SOFTWARE\Python\PythonCore\",
                @"HKCU\SOFTWARE\Python\PythonCore\",
                @"HKLM\SOFTWARE\Wow6432Node\Python\PythonCore\"
            };

            //Version number, install path
            Dictionary<string, string> pythonLocations = new Dictionary<string, string>();

            foreach (string possibleLocation in possiblePythonLocations) {
                string regKey = possibleLocation.Substring(0, 4), actualPath = possibleLocation.Substring(5);
                RegistryKey theKey = (regKey == "HKLM" ? Registry.LocalMachine : Registry.CurrentUser);
                RegistryKey theValue = theKey.OpenSubKey(actualPath);

                foreach (var v in theValue.GetSubKeyNames()) {
                    RegistryKey productKey = theValue.OpenSubKey(v);
                    if (productKey != null) {
                        try {
                            string pythonExePath = productKey.OpenSubKey("InstallPath").GetValue("ExecutablePath").ToString();
                            
                            // Comment this in to get (Default) value instead
                            // string pythonExePath = productKey.OpenSubKey("InstallPath").GetValue("").ToString();
                            
                            if (pythonExePath != null && pythonExePath != "") {
                                //Console.WriteLine("Got python version; " + v + " at path; " + pythonExePath);
                                pythonLocations.Add(v.ToString(), pythonExePath);
                            }
                        } catch {
                            //Install path doesn't exist
                        }
                    }
                }
            }

            if (pythonLocations.Count > 0) {
                System.Version desiredVersion = new System.Version(requiredVersion == "" ? "0.0.1" : requiredVersion),
                    maxPVersion = new System.Version(maxVersion == "" ? "999.999.999" : maxVersion);

                string highestVersion = "", highestVersionPath = "";

                foreach (KeyValuePair<string, string> pVersion in pythonLocations) {
                    //TODO; if on 64-bit machine, prefer the 64 bit version over 32 and vice versa
                    int index = pVersion.Key.IndexOf("-"); //For x-32 and x-64 in version numbers
                    string formattedVersion = index > 0 ? pVersion.Key.Substring(0, index) : pVersion.Key;

                    System.Version thisVersion = new System.Version(formattedVersion);
                    int comparison = desiredVersion.CompareTo(thisVersion),
                        maxComparison = maxPVersion.CompareTo(thisVersion);

                    if (comparison <= 0) {
                        //Version is greater or equal
                        if (maxComparison >= 0) {
                            desiredVersion = thisVersion;

                            highestVersion = pVersion.Key;
                            highestVersionPath = pVersion.Value;
                        } else {
                            //Console.WriteLine("Version is too high; " + maxComparison.ToString());
                        }
                    } else {
                        //Console.WriteLine("Version (" + pVersion.Key + ") is not within the spectrum.");
                    }
                }

                //Console.WriteLine(highestVersion);
                //Console.WriteLine(highestVersionPath);
                return highestVersionPath;
            }

            return "";
        }
dgjrabp2

dgjrabp22#

您可以通过在windows机器上查找以下键来找到python安装路径。

HKLM\SOFTWARE\Python\PythonCore\versionnumber\InstallPath

HKCU\SOFTWARE\Python\PythonCore\versionnumber\InstallPath

用于win64位计算机

HKLM\SOFTWARE\Wow6432Node\Python\PythonCore\versionnumber\InstallPath

您可以参考此帖子了解如何使用C#读取注册表
How to read value of a registry key c#

rseugnpd

rseugnpd3#

在Windows中找到该程序集的环境变量名,并使用Environment.GetEnvironmentVariable(variableName)
checkout How to add to the pythonpath in windows 7?

cngwdvgl

cngwdvgl4#

下面是一个关于如何在PATH环境变量中搜索Python的示例:

var entries = Environment.GetEnvironmentVariable("path").Split(';');
string python_location = null;

foreach (string entry in entries)
{
    if (entry.ToLower().Contains("python"))
    {
        var breadcrumbs = entry.Split('\\');
        foreach (string breadcrumb in breadcrumbs)
        {
            if (breadcrumb.ToLower().Contains("python"))
            {
                python_location += breadcrumb + '\\';
                break;
            }
            python_location += breadcrumb + '\\';
        }
        break;
    }
}
l0oc07j2

l0oc07j25#

如果已经设置了python env路径,只需将FileName更改为“python.exe

private void runPython(string cmd, string args)
    {
        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = "python.exe";
        start.Arguments = string.Format("{0} {1}", cmd, args);
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;
        using (Process process = Process.Start(start))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                Console.Write(result);
            }
        }
    }
8ehkhllq

8ehkhllq6#

在我的机器上,安装了Python 3.11,我可以通过定义以下属性来查询它:

public string PythonInstallPath 
{ 
   get => (string)Microsoft.Win32.Registry.GetValue(
          @"HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\3.11\InstallPath",
          "ExecutablePath", null); 
}

Pythonw.exe位于同一路径中,因此您可以执行以下操作:

public string PythonWInstallPath 
{ 
   get => System.IO.Path.Combine(System.IO.Path.GetDirectoryName(PythonInstallPath), 
                                 "pythonw.exe"); 
}

还有一种方法可以在环境中查找它,选择this out作为替代。

相关问题