@@ -51,10 +51,36 @@ def panel_url(self) -> str:
5151 return self ._panel_url
5252
5353 def _get_python_path (self ) -> str :
54- """Get the Python path for the panel."""
54+ """Get the Python interpreter path for the panel that ensures the same environment."""
55+ if sys .executable is None or sys .executable == "" :
56+ raise RuntimeError ("Python environment not found" )
5557 if getattr (sys , "frozen" , False ):
5658 raise RuntimeError ("Panel cannot be used in a frozen application (e.g., PyInstaller)." )
57- python_path = str (Path (sys .executable ).resolve ())
58- if python_path is None or python_path == "" :
59- raise RuntimeError ("Python environment not found" )
59+
60+ if sys .prefix != sys .base_prefix :
61+ # If we're in a virtual environment, build the path to the Python executable
62+ # On Linux: .venv/bin/python, On Windows: .venv\Scripts\python.exe
63+ if sys .platform .startswith ("win" ):
64+ python_executable = "python.exe"
65+ bin_dir = "Scripts"
66+ else :
67+ python_executable = "python"
68+ bin_dir = "bin"
69+
70+ # Construct path to the Python in the virtual environment based on sys.prefix
71+ python_path = str (Path (sys .prefix ) / bin_dir / python_executable )
72+
73+ # Fall back to sys.executable if the constructed path doesn't exist
74+ if not Path (python_path ).exists ():
75+ python_path = str (Path (sys .executable ).resolve ())
76+ else :
77+ # If not in a .venv environment, use sys.executable
78+ python_path = str (Path (sys .executable ).resolve ())
79+
80+ if sys .prefix not in python_path :
81+ # Ensure the Python path is within the current environment
82+ raise RuntimeError (
83+ f"Python path '{ python_path } ' does not match the current environment prefix '{ sys .prefix } '."
84+ )
85+
6086 return python_path
0 commit comments