Last active
April 5, 2020 13:03
-
-
Save estysdesu/21a96bba020bac9198497332b9b1864c to your computer and use it in GitHub Desktop.
[Python: Check Existence in PATH] #shell #shutil #subprocess #path #which #python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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