Home > Programming & scripting, Python > Getting output of a system-call in python

Getting output of a system-call in python

January 9th, 2007

I was playing around a bit with os.system() in python trying to get the verbosed output and not the returnvalue into a variable.
I wanted to use identify from imagemagick and get the image information, but didn’t find much about how to do that until I ran into The subprocess module.

I didn’t even know that this existed in python, but that could just be me. Anyways, a fast way to get the verbosed output of a script/application:

import subprocess, os
command = "uptime"
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
os.waitpid(process.pid, 0)
output = process.stdout.read().strip()

Output now contains the output of the command, in this case:
“18:58:09 up 4 days, 17:24, 37 users, load average: 0.18, 0.25, 0.26″

buffi Programming & scripting, Python

  1. Arupendu
    October 2nd, 2007 at 13:25 | #1

    Thanx i was also searching for a similar process where i can pipeline the output of shell to some variable or other process.
    i tried this and ogt successfull

    import subprocess, os
    command = “dir”
    process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
    process.communicate()[0]

    Those who want to learn more can read
    http://pydoc.org/2.4.1/subprocess.html

  2. April 11th, 2008 at 08:12 | #2

    It’s gratifying to see not only that such positive things happen, but that they are being REPORTED.

  3. Zubair
    May 18th, 2009 at 08:09 | #3

    Thanks. You got me the right tip! (y)

  4. October 17th, 2009 at 22:35 | #4

    Hey, Thanks for posting this. It was exactly what I was needed for a project.

  1. No trackbacks yet.