Main Content
Running operating system commands from your Python program Archive - Originally posted on "The Horse's Mouth" - 2010-05-14 12:33:29 - Graham Ellis
As from Python 2.6, os.popen and friends are deprecated methods and you should use the subprocess module for subprocesses. So that's the way to go if you want to run operating system commands. New example showing this - [here]
Starting with:
from subprocess import *
I can run a process and allow its output to to stdout via the call utility:
stuff0 = call("ls")
I can run a process and capture its output to a variable (2 examples):
stuff1 = Popen(["ls"], stdout=PIPE).communicate()[0]
stuff2 = Popen(["ls","-l"], stdout=PIPE).communicate()[0]
And I can open a process that I can then read back from it (2 more examples):
pingalong = Popen("ping -q -c2 192.168.200.134", shell=True, stdout=PIPE).stdout
pingalot = Popen(["ping","-q","-c2","192.168.200.115"], stdout=PIPE).stdout
Note the use of shell=True to push the incoming command through the shell, rather than have to split up the command and parameters yourself.
Some other articles
Y303 - Python Network Programming Python network programming - new FTP and socket level examples This article TCP v UDP / Client v Server - Python examples Multiple processes (forking) in Python Python - fresh examples of all the fundamentals Counting Words in Python via the web Y115 - Additional Python Facilities Some gems from Intermediate Python Command line parameter handling in Python via the argparse module Json load from URL, recursive display, Python 3.4 Running an operating system command from your Python program - the new way with the subprocess module Json is the new marshall, pickle and cPickle / Python Python - an interesting application Handling JSON in Python (and a csv, marshall and pickle comparison) JSON from Python - first principles, easy example Teaching dilemma - old tricks and techniques, or recent enhancements? A demonstration of how many Python facilities work together Python regular expressions - repeating, splitting, lookahead and lookbehind Joining a MySQL table from within a Python program Factory methods and SqLite in use in a Python teaching example This article Python decorators - your own, staticmethod and classmethod Model - View - Controller demo, Sqlite - Python 3 - Qt4 Connecting Python to sqlite and MySQL databases Regular Expressions in Python Python - what is going on around me? Python - how it saves on compile time Serialization - storing and reloading objects Testing code in Python - doctest, unittest and others Python Regular Expressions A series of tyre damages Ignore case in Regular Expression Regular expressions made easy - building from components Turning objects into something you can store - Pickling (Python) Buffering output - why it is done and issues raised in Tcl, Perl, Python and PHP Sending an email from Python Python - listing out the contents of all variables Python 3000 - the next generation Keeping your regular expressions simple Python to MySQL Splitting the difference What and why for the epoch Examples - Gadfly, NI Number, and Tcl to C interface The elegance of Python Y108 - String Handling Prining a pound sign from Python AND running from the command line at the same time Python formatting update - including named completions Command line parameter handling in Python via the argparse module Python - comparison of old and new string formatters Identifying and clearing denial of service attacks on your Apache server Formatting options in Python Why are bus fares so high? Collections in Python - list tuple dict and string. Formatting output - why we need to, and first Python example Backquote, backtic, str and repr in Python - conversion object to string Teaching dilemma - old tricks and techniques, or recent enhancements? Python string formatting - the move from % to str.format Formatting output in Python through str.format Matching a license plate or product code - Regular Expressions Matching to a string - what if it matches in many possible ways? Python - splitting and joining strings Formatted Printing in Python This article Regular Expressions in Python Flexible search and replace in Python Pound Sign in Python Program Strings as collections in Python Python Regular Expressions Underlining in Perl and Python - the x and * operator in use Python - formatting objects Regular Express Primer Python - two different splits String duplication - x in Perl, * in Python and Ruby Splitting Pythons in Bradford Matching within multiline strings, and ignoring case in regular expressions Pieces of Python Breaking bread The fencepost problem Python printf Splitting the difference The backtick operator in Python and Perl