Skip to content

Commit 9e6ffba

Browse files
committed
Derive program name from venv if possible
1 parent 8d8bf26 commit 9e6ffba

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

src/runtime/Runtime.cs

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Text;
66
using System.Threading;
77
using System.Collections.Generic;
8+
using System.IO;
89
using Python.Runtime.Native;
910
using System.Linq;
1011
using static System.FormattableString;
@@ -33,7 +34,8 @@ public static string? PythonDLL
3334
private static string? GetDefaultDllName()
3435
{
3536
string dll = Environment.GetEnvironmentVariable("PYTHONNET_PYDLL");
36-
if (dll is not null) return dll;
37+
if (!string.IsNullOrEmpty(dll))
38+
return dll;
3739

3840
string verString = Environment.GetEnvironmentVariable("PYTHONNET_PYVER");
3941
if (!Version.TryParse(verString, out var version)) return null;
@@ -96,6 +98,42 @@ internal static int GetRun()
9698
return runNumber;
9799
}
98100

101+
static void EnsureProgramName()
102+
{
103+
if (!string.IsNullOrEmpty(PythonEngine.ProgramName))
104+
return;
105+
106+
string fromEnv = Environment.GetEnvironmentVariable("PYTHONNET_PYEXE");
107+
if (!string.IsNullOrEmpty(fromEnv))
108+
{
109+
PythonEngine.ProgramName = fromEnv;
110+
return;
111+
}
112+
113+
string venv = Environment.GetEnvironmentVariable("VIRTUAL_ENV");
114+
if (!string.IsNullOrEmpty(venv))
115+
{
116+
if (IsWindows)
117+
{
118+
var path = Path.Combine(venv, "Scripts", "python.exe");
119+
if (System.IO.File.Exists(path))
120+
{
121+
PythonEngine.ProgramName = path;
122+
return;
123+
}
124+
}
125+
else
126+
{
127+
var path = Path.Combine(venv, "bin", "python");
128+
if (System.IO.File.Exists(path))
129+
{
130+
PythonEngine.ProgramName = path;
131+
return;
132+
}
133+
}
134+
}
135+
}
136+
99137
internal static bool HostedInPython;
100138
internal static bool ProcessIsTerminating;
101139

@@ -117,6 +155,8 @@ internal static void Initialize(bool initSigs = false)
117155
);
118156
if (!interpreterAlreadyInitialized)
119157
{
158+
EnsureProgramName();
159+
120160
Py_InitializeEx(initSigs ? 1 : 0);
121161

122162
NewRun();

0 commit comments

Comments
 (0)