我正在做一个使用python作为后台脚本和C#作为GUI的项目。 我的问题是我不知道如何让我的 GUI 自动搜索
pythonw.exe
文件以运行我的 python 脚本。
目前我正在使用这条路径:
ProcessStartInfo pythonInfo = new ProcessStartInfo(@"C:\\Users\\Omri\\AppData\\Local\\Programs\\Python\\Python35-32\\pythonw.exe");
但我希望它自动检测
pythonw.exe
的路径(我需要提交项目,它不会在其他计算机上运行,除非他们更改代码本身)
任何建议都可能有帮助。
受到@Shashi Bhushan回答的启发,我做了这个函数来可靠地获取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())
if (theValue.OpenSubKey(v) is RegistryKey productKey)
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(requiredVersion == "" ? "0.0.1" : requiredVersion);
System.Version maxPVersion = new(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 "";
}
您可以通过在Windows机器上查找以下键来找到Python的安装路径。
HKLM\SOFTWARE\Python\PythonCore\versionnumber\InstallPath
HKCU\SOFTWARE\Python\PythonCore\versionnumber\InstallPath
适用于win64位机器
HKLM\SOFTWARE\Wow6432Node\Python\PythonCore\versionnumber\InstallPath
您可以参考这篇文章了解如何使用C#读取注册表
在 Windows 中查找该程序集的环境变量名称并使用
Environment.GetEnvironmentVariable(variableName)
如何在 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;
}
}
如果您已经设置了 python env 路径,只需将文件名更改为“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);
}
}
}
在我的机器上,安装了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作为替代方案。
使用此片段:
public string FindPythonPath()
{
using (var hiveKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default))
using (var subkey = hiveKey?.OpenSubKey(@"SOFTWARE\Python\PythonCore"))
{
var subkeys = subkey?.GetSubKeyNames();
if (subkeys.Length == 0) return string.Empty;
var key = hiveKey.OpenSubKey(@"SOFTWARE\Python\PythonCore\"+subkeys.Last());
key = key.OpenSubKey("InstallPath");
return Path.GetDirectoryName((string) key.GetValue("ExecutablePath", string.Empty));
}
}