1

I want to use Python's subprocess.check_output to check if the command python is in PATH and its version. The funny thing is that check_output is able to run the command python even if it's not in PATH:

C:\Users\Aivar\Desktop>set PATH=blahblah

C:\Users\Aivar\Desktop>python --version
'python' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\Aivar\Desktop>c:\python35\python -c ^
More? "import subprocess; ^
More? print(subprocess.check_output(['python', '--version']))"
b'Python 3.5.1\r\n'

C:\Users\Aivar\Desktop>c:\python35\python -c ^
More? "import os; print(os.environ['PATH'])"
blahblah

Can someone explain what's going on?

Eryk Sun
  • 33,190
  • 5
  • 92
  • 111
Aivar
  • 6,814
  • 5
  • 46
  • 78
  • Can it be that the location of parent executable (`c:\python35\python` in my case) affects the search of commands? Can someone confirm this? – Aivar Dec 22 '15 at 13:54
  • Try and check what `subprocess.check_output(['echo', '%CD%'])` returns to see your working directory. – gietljohannes Dec 22 '15 at 14:12
  • @JoeZocker, your snippet shows that working directory is the same where I executed Python and what is shown in the shell prompt – Aivar Dec 22 '15 at 14:58
  • Check out [This](http://stackoverflow.com/a/5659249/3714940) answer. Add `shell = True` to your `check_output()` call and you should get the expected outcome (I get `'python' is not recognized as an internal or external command...`) – SiHa Dec 22 '15 at 16:43
  • 1
    [`CreateProcess`](https://msdn.microsoft.com/en-us/library/ms682425) always checks the application directory first, followed by the working directory, `%SystemRoot%\System32`, `%SystemRoot%`, and then the `PATH` directories. – Eryk Sun Dec 22 '15 at 17:35
  • In Vista+ you can force `CreateProcess` and cmd.exe to skip searching the working directory (but not the application directory) by defining the environment variable [`NoDefaultCurrentDirectoryInExePath`](https://msdn.microsoft.com/en-us/library/ms684269). – Eryk Sun Dec 22 '15 at 17:37
  • 1
    If you define an [`App Paths` key](https://msdn.microsoft.com/en-us/library/ee872121#appPaths) for Python, then you can run `start python` from the command prompt, or to have cmd use the current console window and wait, for example, `start /b /w python -c "import sys; print(sys.executable)"`. In your case you can add this key from the command prompt using `reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\App Paths\python.exe" /ve /d "\"C:\Python35\python.exe\""`. – Eryk Sun Dec 22 '15 at 17:47

0 Answers0