200509: Making System Calls (with unix and Python 2.4)
To make a system call, use:
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:
last_line=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
--------
this post is archived at
http://xahlee.org/perl-python/system_calls.html
☄