How do you execute a external command i.e. the way it is typed in cmd (Windows command prompt) or Unix Shell command from Python?
Use the python subprocess library to execute as shown below
import subprocess
import platform
Check your python version by running the below command:
Google Colab:
!python3 --version
Jupyter Notebook:
platform.python_version()
Windows:
For Python Version <3.7:
subprocess.check_output("dir/s", shell=True)
Output:
For Python Version >3.7:
subprocess.run(["dir"],shell=True, capture_output=True)
Output:
Linux:
For Python Version <3.7:
subprocess.run(["ls", "-l"],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Output:
For Python Version >3.7:
subprocess.run(["dir"],shell=True, capture_output=True)
Output:
Notes:
shell=True:
- If passing a single string, either shell must be True
- Or
- String passed must simply name the program to be executed without specifying any arguments