PyMOTW: sys, Part 2: Runtime Environment

By Doug Hellmann
October 18, 2009

Runtime Environment

sys provides low-level APIs for interacting with the system outside of your application, by accepting command line arguments, accessing user input, and passing messages and status values to the user.

Arguments to Your Program

The arguments captured by the interpreter are processed there and not passed along to your program directly. Any remaining options and arguments, including the name of the script itself, are saved to sys.argv in case your program does need to use them.

import sys

print 'Arguments:', sys.argv
$ python sys_argv.py
Arguments: ['sys_argv.py']
$ python sys_argv.py -v foo blah
Arguments: ['sys_argv.py', '-v', 'foo', 'blah']

See also

getopt, optparse
Modules for parsing command line arguments.

Input and Output Steams

Following the Unix paradigm, Python programs can access three file descriptors by default. stdin is the standard way to read input, usually from a console but also from other programs via a pipeline. stdout is the standard way to write output for a user (to the console) or to be sent to the next program in a pipeline. stderr is intended for use with warning or error messages.

import sys

print >>sys.stderr, 'STATUS: Reading from stdin'

data = sys.stdin.read()

print >>sys.stderr, 'STATUS: Writing data to stdout'

sys.stdout.write(data)
sys.stdout.flush()

print >>sys.stderr, 'STATUS: Done'
$ cat sys_stdio.py | python sys_stdio.py
STATUS: Reading from stdin
STATUS: Writing data to stdout
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2009 Doug Hellmann All rights reserved.
#
"""
"""
#end_pymotw_header

import sys

print >>sys.stderr, 'STATUS: Reading from stdin'

data = sys.stdin.read()

print >>sys.stderr, 'STATUS: Writing data to stdout'

sys.stdout.write(data)
sys.stdout.flush()

print >>sys.stderr, 'STATUS: Done'
STATUS: Done

See also

subprocess, pipes
Both subprocess and pipes have features for pipelining programs together.

Returning Status

To return an exit code from your program, pass an integer value to sys.exit(). A non-zero value means the program exited with an error.

import sys

exit_code = int(sys.argv[1])
sys.exit(exit_code)
$ python sys_exit.py 0 ; echo "Exited $?"
Exited 0
$ python sys_exit.py 1 ; echo "Exited $?"
Exited 1

PyMOTW Home

The canonical version of this article


You might also be interested in:

News Topics

Recommended for You

Got a Question?