MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1&1

Making System Calls in Perl & Python

Xah Lee, 2005-09, 2011-01

If you work with unix, often it is convenient to use the unix's command line tool bag. 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:

import subprocess
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.

Following is a complete example. The code makes a system call to decompress a gzip file (and wait for it), then get the last line of the file by calling the unix util “tail”, then gzip the file 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

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:

# -*- coding: utf-8 -*-
# perl

qx(gzip x.txt);
qx(gzip -d x.txt.gz);
blog comments powered by Disqus