Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 weird behavior of subprocess.call

Environment:

Windows: 10
Python: 2.7.13 and 3.8.1
default Python launcher: py -3
Default python: 2.7.13

> python -V
> Python 2.7.13

> py -3 -V
> Python 3.8.1



launcher.py:

import subprocess
subprocess.call(['python', '-V'])


  1. Test 1: py -3 launcher.py

    Output: python 3.8.1 (HOW!)

  2. Test 2: py -2 launcher.py

    Output: Python 2.7.13


The output should be Python 2.7.13 only, even the launcher runs under py 3!
note that, adding shell=True will work, but the idea is not to use it, and if I ran

subprocess.call(['python', 'script_under_py_2.py']) # Will run python 3 with script python 2!

Thanks
Adam

like image 554
آدم قنوات Avatar asked Dec 05 '25 20:12

آدم قنوات


1 Answers

This behavior is due to the inconsistent handling of the PATH environment variable when calling Popen on Windows and Unix.

Windows creates its sub-processes using CreateProcess function. The search path for CreateProcess includes parent process directory, which may be the reason why you are having different binaries executed.

On Windows, PATH is only considered when shell=True is also passed.

You can learn more about the issue here:

  • subprocess PATH semantics and portability (notice the "needs patch" stage)
like image 142
Pavel Vergeev Avatar answered Dec 08 '25 11:12

Pavel Vergeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!