subprocess has wrong pid on Windows

Viewed 432

main.py:

from subprocess import Popen
import sys

proc = Popen([sys.executable, 'sub.py'])
print('parent thinks subprocess pid is', proc.pid)

sub.py:

import os
print('subprocess thinks its pid is', os.getpid())

Output of python main.py on Linux:

parent thinks subprocess pid is 338
subprocess thinks its pid is 338

Output on Windows:

parent thinks subprocess pid is 17340
subprocess thinks its pid is 7308

Why is this?

Edit: print(sys.executable) gives C:\my-venv\Scripts\python.exe

1 Answers

When creating virtual environment on windows, it looks like that the python interpreter copied to venv's Script folder is not the actual python executable but a wrapper that executes it.

If you modify sub.py to be something like this:

import os
import psutil
local_pid = os.getpid()
parent = psutil.Process(local_pid).parent()
print('subprocess thinks its pid is', os.getpid())
try:
    print("parent process of our main python is", parent.pid)
except:
    pass

You will see that os.getpid() will return its own pid but it has a parent when executed inside virtual env. However, when venv is deactivated, main and sub.py do report the same pid.

Related