Calling / Run / Execute an External Command from Python

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:

Calling an external command from Python

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:

Calling an external command from Python

For Python Version >3.7:

subprocess.run(["dir"],shell=True, capture_output=True)

Output:

Calling an external command from Python

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

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.