Making System Calls in Perl and Python

Xah Lee, 2005-09

If you work with unix, often it is convenient to use the unix's command line toolbag. Although this makes your program less portable, but for most unix sys admin tasks it doesn't matter.

In this page, we show how to make a system call with Python 2.4 and Perl.

Python

Suppose you want to run the command “gzip -d x.txt.gz”. To call this in Python, do:

subprocess.Popen([r"gzip","-d", "x.txt.gz"]).wait()

The subprocess module is available only since Python 2.4, and it is intended to replace several other older ones:

os.system
os.spawn*
os.popen*
popen2.*
commands.*

The subprocess.Popen([...]) creates a object. The .wait() makes the code wait until the system call finished. To not wait for it, simply use:

subprocess.Popen([r"gzip","-d", "x.txt.gz"])

To make a system call and get its output, do, for example:

myOutput=subprocess.Popen([r"tail","-n 1", "x.txt"], stdout=subprocess.PIPE).communicate()[0]

The “communicate()” automatically makes the call wait.

In the following example, we make a system call to decompress a gzip file (and wait for it), then get the last line of the file using “tail”, then gzip it again.

# -*- coding: utf-8 -*-
# Python

import subprocess

subprocess.Popen([r"gzip","-d", "x.txt.gz"]).wait()

last_line=subprocess.Popen([r"tail","-n 1", "x.txt"], stdout=subprocess.PIPE).communicate()[0]

subprocess.Popen([r"gzip","x.txt"]).wait()

print last_line

Reference: http://www.python.org/doc/2.4/lib/module-subprocess.html

Perl

In Perl, to do a system call, use “qx()” or “system()”. The qx command returns unix's stdout and do wait for the process to finish. Example:

# perl

qx(gzip x.txt);
qx(gzip -d x.txt.gz);

Reference: perldoc perlop↗.

Reference: perldoc -f qx↗.

Reference: perldoc -f system↗.


See also:


Page created: 2005-09.
© 2005 by Xah Lee.
Xah Signet