我正在使用C#中的ArcMap加载项。从C#代码中,我已经执行了一些Python脚本。现在,要运行这些脚本,我已对python路径进行了硬编码。但这不是便携式的。因此,我想从代码中获取Python可执行文件的路径并使用它。
题:
如何从C#代码获取ArcMap使用的Python可执行文件的路径?
编辑:
根据您的建议,现在我正在使用“路径环境”来获取Python路径。
//get python path from environtment variable
string GetPythonPath()
{
IDictionary environmentVariables = Environment.GetEnvironmentVariables();
string pathVariable = environmentVariables["Path"] as string;
if (pathVariable != null)
{
string[] allPaths = pathVariable.Split(';');
foreach (var path in allPaths)
{
string pythonPathFromEnv = path + "\\python.exe";
if (File.Exists(pythonPathFromEnv))
return pythonPathFromEnv;
}
}
}
但有个问题:
当我的计算机上安装了不同版本的python时,无法保证我正在使用的“ python.exe”,ArcGIS也正在使用该版本。
我不喜欢使用其他工具来获取“ python.exe”路径。因此,我真的认为是否有任何方法可以从注册表项中获取路径。对于“ ArcGIS10.0”注册表看起来像:
为此,我正在考虑以下途径:
//get python path from registry key
string GetPythonPath()
{
const string regKey = "Python";
string pythonPath = null;
try
{
RegistryKey registryKey = Registry.LocalMachine;
RegistryKey subKey = registryKey.OpenSubKey("SOFTWARE");
if (subKey == null)
return null;
RegistryKey esriKey = subKey.OpenSubKey("ESRI");
if (esriKey == null)
return null;
string[] subkeyNames = esriKey.GetSubKeyNames();//get all keys under "ESRI" key
int index = -1;
/*"Python" key contains arcgis version no in its name. So, the key name may be
varied version to version. For ArcGIS10.0, key name is: "Python10.0". So, from
here I can get ArcGIS version also*/
for (int i = 0; i < subkeyNames.Length; i++)
{
if (subkeyNames[i].Contains("Python"))
{
index = i;
break;
}
}
if(index < 0)
return null;
RegistryKey pythonKey = esriKey.OpenSubKey(subkeyNames[index]);
string arcgisVersion = subkeyNames[index].Remove(0, 6); //remove "python" and get the version
var pythonValue = pythonKey.GetValue("Python") as string;
if (pythonValue != "True")//I guessed the true value for python says python is installed with ArcGIS.
return;
var pythonDirectory = pythonKey.GetValue("PythonDir") as string;
if (pythonDirectory != null && Directory.Exists(pythonDirectory))
{
string pythonPathFromReg = pythonDirectory + "ArcGIS" + arcgisVersion + "\\python.exe";
if (File.Exists(pythonPathFromReg))
pythonPath = pythonPathFromReg;
}
}
catch (Exception e)
{
MessageBox.Show(e + "\r\nReading registry " + regKey.ToUpper());
pythonPath = null;
}
return pythonPath ;
}
但是在使用第二个步骤之前,我需要确定自己的猜测。猜测是:
- 与python关联的“ True”表示Python已与ArcGIS一起安装
- ArcGIS 10.0和更高版本的注册表项将在同一过程中编写。
请帮助我澄清我的猜测。