Skip to content

Commit 5464ce8

Browse files
committed
Add support for finding default python home
1 parent 7fc00f8 commit 5464ce8

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/Bonsai.Scripting.Python/EnvironmentHelper.cs

+23-1
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,34 @@ public static void SetRuntimePath(string pythonHome)
2424
}
2525
}
2626

27+
static string FindPythonHome()
28+
{
29+
var systemPath = Environment.GetEnvironmentVariable("PATH");
30+
var searchPaths = systemPath.Split(Path.PathSeparator);
31+
var isRunningOnWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
32+
var pythonExecutableName = isRunningOnWindows ? "python.exe" : "python3";
33+
34+
var pythonHome = Array.Find(searchPaths, path => File.Exists(Path.Combine(path, pythonExecutableName)));
35+
if (pythonHome != null && !isRunningOnWindows && MonoHelper.IsRunningOnMono)
36+
{
37+
var pythonExecutablePath = Path.Combine(pythonHome, pythonExecutableName);
38+
pythonExecutablePath = MonoHelper.GetRealPath(pythonExecutablePath);
39+
var baseDirectory = Directory.GetParent(pythonExecutablePath).Parent;
40+
if (baseDirectory != null)
41+
{
42+
pythonHome = Path.Combine(baseDirectory.FullName, "lib", Path.GetFileName(pythonExecutablePath));
43+
}
44+
}
45+
46+
return pythonHome;
47+
}
48+
2749
public static string GetEnvironmentPath(string path)
2850
{
2951
if (string.IsNullOrEmpty(path))
3052
{
3153
path = Environment.GetEnvironmentVariable("VIRTUAL_ENV", EnvironmentVariableTarget.Process);
32-
if (path == null) return path;
54+
if (path == null) return FindPythonHome();
3355
}
3456

3557
return Path.GetFullPath(path);
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using System;
2+
3+
namespace Bonsai.Scripting.Python
4+
{
5+
static class MonoHelper
6+
{
7+
internal static readonly bool IsRunningOnMono = Type.GetType("Mono.Runtime") != null;
8+
9+
public static string GetRealPath(string path)
10+
{
11+
var unixPath = Type.GetType("Mono.Unix.UnixPath, Mono.Posix");
12+
if (unixPath == null)
13+
{
14+
throw new InvalidOperationException("No compatible Mono.Posix implementation was found.");
15+
}
16+
17+
var getRealPath = unixPath.GetMethod(nameof(GetRealPath));
18+
if (getRealPath == null)
19+
{
20+
throw new InvalidOperationException($"No compatible {nameof(GetRealPath)} method was found.");
21+
}
22+
23+
return (string)getRealPath.Invoke(null, new[] { path });
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)