License New BSD license
Lines 47
Keywords
command (1) command line (1) system (1)
Permissions
Viewable by Everyone
Editable by All Siafoo Users
Hide
Easily highlight source code for your blog with our Syntax Highlighter. Join Siafoo Now or Learn More

Better Command-Line Calls Atom Feed 0

In Brief A better way to do command-line system calls in Python. On call, can report command, output, and/or errors.... more
# 's
 1# Copyright 2007 Regents of the University of California
2# Written by David Isaacson at the University of California, Davis
3# BSD License
4
5import os, sys
6
7class SystemCommand:
8 dry_run = 0
9
10
11 def __init__(self, quiet=0, dry_run = 0):
12 self.dry_run = dry_run
13
14
15 def system(self,command,quiet=None,handled=[]):
16 #quiet = 0: report command and output
17 #quiet = 1: report command only
18 #quiet = 2: report nothing
19 if quiet is None: quiet=self.quiet
20 if quiet != 2:
21 print command
22 if self.dry_run:
23 return [0,""]
24 command += " 2>&1"
25 fd = os.popen(command,"r",1)
26
27 output = ""
28 while True:
29 char = fd.read(1)
30 if not char:
31 break
32 output += char
33 if quiet == 0:
34 sys.stdout.write(char)
35
36 err = fd.close()
37 if err:
38 err = int(err)/256
39 for handle in handled:
40 if err == handle:
41 return [err,output]
42
43 #on unhandled err, disable quiet
44 if quiet == 2: print command
45 if quiet != 0: sys.stdout.write(output)
46 print
47 print "ERROR: A system call did not exit cleanly."
48 print " Command:",command
49 print " Error Code:",err
50 print "Exiting."
51 print
52 sys.exit()
53
54 return [0,output]

A better way to do command-line system calls in Python. On call, can report command, output, and/or errors.

Pass dry_run = 1 to only report the command, without actually running it. Pass quiet = 0 (default) to suppress output, quiet = 1 to suppress output but print command, and quiet = 2 to print command and output.

Also accepts a list of integer error codes to ignore for the command. If a different error occurs, will exit the program via sys.exit().

The class can be initialized once and used many times, or the function 'system' could be used independently with a few minor modifications.

Comments

over 9 years ago (21 Mar 2008 at 06:24 PM) by Stou S.
There's also the "new" sub-process management module in Python http://docs.python.org/lib/module-subprocess.html
over 9 years ago (26 Mar 2008 at 10:01 PM) by David Isaacson
Ooh, that looks cool. Someone should write an article about it :-D