Python: Run External Program Command

This post will guide you how to run external programs or commands from python and retrieve the output and return code. How do I run external command in python using Popen module. How to execute shell commands in Python.

Run External Program


If you want to run external programs or shell commands in a python script, you can refer to the following methods.

Method1: Call an external command or program using os.system module

The os.system module will pass the command and its arguments to shell program.  For example, Run a date command in a python script:

>>> import os
>>> os.system("date")
Sun Sep 16 22:13:57 EDT 2018

Method2: Call an external command or program using subprocess moduel

Type:

>>> import subprocess
>>> subprocess.call("date")

Sun Sep 16 22:24:37 EDT 2018

Method3: Call an external command using Popen

Type:

>>> import subprocess
>>> print subprocess.Popen("date", shell=True, stdout=subprocess.PIPE).stdout.read()
Sun Sep 16 22:26:44 EDT 2018

 

You might also like:

Sidebar



back to top