Python Execute Unix / Linux Command Examples

by on November 9, 2012 · 7 comments· LAST UPDATED December 30, 2013

in , ,

How do I execute standard Unix or Linux shell commands using Python? Is there a command to invoke Unix commands using Python programs?

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
Estimated completion timeN/A

You can execute the command in a subshell using os.system(). This will call the Standard C function system(). This function will return the exit status of the process or command. This method is considered as old and not recommended, but presented here for historical reasons only. The subprocess module is recommended and it provides more powerful facilities for running command and retrieving their results.

os.system example (deprecated)

The syntax is:

import os

In this example, execute the date command:

import os

Sample outputs:

Sat Nov 10 00:49:23 IST 2012

In this example, execute the date command using os.popen() and store its output to the variable called now:

import os
f = os.popen('date')
now =
print "Today is ", now

Sample outputs:

Today is  Sat Nov 10 00:49:23 IST 2012

Say hello to subprocess

The os.system has many problems and subprocess is a much better way to executing unix command. The syntax is:

import subprocess"command1")["command1", "arg1", "arg2"])

In this example, execute the date command:

import subprocess"date")

Sample outputs:

Sat Nov 10 00:59:42 IST 2012

You can pass the argument using the following syntax i.e run ls -l /etc/resolv.conf command:

import subprocess["ls", "-l", "/etc/resolv.conf"])

Sample outputs:

<-rw-r--r-- 1 root root 157 Nov  7 15:06 /etc/resolv.conf

To store output to the output variable, run:

import subprocess
p = subprocess.Popen("date", stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
print "Today is", output

Sample outputs:

Today is Sat Nov 10 01:27:52 IST 2012

Another example (passing command line args):

import subprocess
p = subprocess.Popen(["ls", "-l", "/etc/resolv.conf"], stdout=subprocess.PIPE)
output, err = p.communicate()
print "*** Running ls -l command ***\n", output

Sample outputs:

*** Running ls -l command ***
-rw-r--r-- 1 root root 157 Nov  7 15:06 /etc/resolv.conf

In this example, run ping command and display back its output:

import subprocess
p = subprocess.Popen(["ping", "-c", "10", ""], stdout=subprocess.PIPE)
output, err = p.communicate()
print  output

The only problem with above code is that output, err = p.communicate() will block next statement till ping is completed i.e. you will not get real time output from the ping command. So you can use the following code to get real time output:

import subprocess
cmdping = "ping -c4"
p = subprocess.Popen(cmdping, shell=True, stderr=subprocess.PIPE)
while True:
    out =
    if out == '' and p.poll() != None:
    if out != '':

Sample outputs:

PING ( 56(84) bytes of data.
64 bytes from ( icmp_req=1 ttl=55 time=307 ms
64 bytes from ( icmp_req=2 ttl=55 time=307 ms
64 bytes from ( icmp_req=3 ttl=55 time=308 ms
64 bytes from ( icmp_req=4 ttl=55 time=307 ms
--- ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3001ms
rtt min/avg/max/mdev = 307.280/307.613/308.264/0.783 ms

Related media

A quick video demo of above python code:

HTML 5 Video 01: Python Run External Command And Get Output On Screen or In Variable

Tweet itFacebook itG+ itDownload PDF versionFound an error/typo on this page?

{ 7 comments… read them below or add one }

1 klo November 9, 2012 at 10:22 pm

307 ms?
That’s a long interval ;)


2 Someone November 10, 2012 at 1:00 pm

Hi, please more small and usefull examples with python like it! more code snippets!


3 meow December 6, 2012 at 12:39 pm

A very comprehensive explanation, being useful to beginners to python.


4 javith January 7, 2013 at 10:38 am

where to find the command of linux


5 Gobinda Singh May 12, 2013 at 9:22 am

these commands are very helpfull us….please give more example like this.


6 Fl'âme January 22, 2014 at 10:06 am



7 nanda kishore March 25, 2015 at 6:07 am

What exactly does Shell=True does?
please tell the exact usage of the shell argumet.


Leave a Comment

Tagged as: , , , , , ,

Previous Faq:

Next Faq: