Skip to content

Instantly share code, notes, and snippets.

@estysdesu
Last active April 5, 2020 13:03
Show Gist options
  • Save estysdesu/21a96bba020bac9198497332b9b1864c to your computer and use it in GitHub Desktop.
Save estysdesu/21a96bba020bac9198497332b9b1864c to your computer and use it in GitHub Desktop.
[Python: Check Existence in PATH] #shell #shutil #subprocess #path #which #python
#!/usr/bin/env python3
import shutil, subprocess
cmd = shutil.which("python3")
try:
runner = subprocess.run(cmd, check=True)
except subprocess.CalledProcessError as e: # python3 is not found in path
print(str(e))
exit(1)
#####
runner = subprocess.run([cmd, "--version"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # --> Python 3.7.3
runner.resultcode # --> 0
runner = subprocess.run([cmd, "--version"], shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
runner.resultcode # --> 127; fails bc shell=True is similar to calling `sh python3 --version` which will error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment