Eryk Sun schreef:
On 10/2/20, Gertjan Klein <gkl...@xs4all.nl> wrote:
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

I can't replicate this. I installed pywin32 in a Python 3.8 virtual environment, and double-clicked on the venv\Scripts\python.exe in explorer:

Python 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:52:53) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, win32console, win32process
>>> hwnd = win32console.GetConsoleWindow()
>>> tid, pid = win32process.GetWindowThreadProcessId(hwnd)
>>> pid == os.getpid()
False

I tried to find out what happens, using your other code:

>>> import win32con, win32api
>>> access = win32con.PROCESS_QUERY_LIMITED_INFORMATION
>>> hproc = win32api.OpenProcess(access, False, pid)
>>> executable = win32process.GetModuleFileNameEx(hproc, None)
>>> print(executable)
C:\Temp\Python\Console\venv\Scripts\python.exe
>>> hproc = win32api.OpenProcess(access, False, os.getpid())
>>> win32process.GetModuleFileNameEx(hproc, None)
'C:\\dev\\Python\\Python38\\python.exe'

So, if I understand this correctly, the console is owned by the venv Python, but the running process is the installed Python executable. I'm lost! How did that latter one get involved?

Regards,
Gertjan.
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to