Python 3.8.5 Not Launching
Eryk Sun
eryksun at gmail.com
Fri Oct 2 09:45:52 EDT 2020
On 10/2/20, Gertjan Klein <gklein at xs4all.nl> wrote:
> Eryk Sun wrote:
>
>> If .py files are associated with py.exe or python.exe, then running a
>> .py script either inherits or allocates a console and attaches to it.
>
> Is it possible to determine, from within Python, whether Python
> allocated or inherited the console?
If a console session isn't headless (i.e. it's not a pseudoconsole)
and has a window (i.e. not allocated with CREATE_NO_WINDOW), then the
effective owner of the window is initially the process that allocated
the console session, as long as it's still running and attached. For
example, with "python.exe" (not a launcher) executed from Explorer:
>>> hwnd = win32console.GetConsoleWindow()
>>> tid, pid = win32process.GetWindowThreadProcessId(hwnd)
>>> pid == os.getpid()
True
A problem is the case of a launcher such as "py.exe", or the
"python.exe" launcher used by venv virtual environments. A venv
launcher can be detected by comparing sys.executable with
sys._base_executable. For example, with a venv launcher executed from
Explorer:
>>> hwnd = win32console.GetConsoleWindow()
>>> tid, pid = win32process.GetWindowThreadProcessId(hwnd)
The current process doesn't own the console, but the parent does:
>>> pid == os.getpid()
False
>>> pid == os.getppid()
True
Check whether the parent is a venv launcher:
>>> print(sys.executable)
C:\Temp\env\test38\Scripts\python.exe
>>> print(sys._base_executable)
C:\Program Files\Python38\python.exe
Double check that the parent is the venv launcher:
>>> access = win32con.PROCESS_QUERY_LIMITED_INFORMATION
>>> hproc = win32api.OpenProcess(access, False, pid)
>>> executable = win32process.GetModuleFileNameEx(hproc, None)
>>> os.path.samefile(executable, sys.executable)
True
More information about the Python-list
mailing list