Skip to Content
Python Standard Library
book

Python Standard Library

by Fredrik Lundh
May 2001
Intermediate to advanced content levelIntermediate to advanced
304 pages
6h 12m
English
O'Reilly Media, Inc.
Content preview from Python Standard Library

The sys Module

The sys module provides a number of functions and variables that can be used to manipulate different parts of the Python runtime environment.

Working with Command-line Arguments

The argv list contains the arguments that were passed to the script, when the interpreter was started, as shown in Example 1-66. The first item contains the name of the script itself.

Example 1-66. Using the sys Module to Get Script Arguments

File: sys-argv-example-1.py

import sys

print "script name is", sys.argv[0]

if len(sys.argv) > 1:
    print "there are", len(sys.argv)-1, "arguments:"
    for arg in sys.argv[1:]:
        print arg
else:
    print "there are no arguments!"

script name is sys-argv-example-1.py
there are no arguments!

If you read the script from standard input (like python < sys-argv-example-1.py), the script name is set to an empty string. If you pass in the program as a string (using the -c option), the script name is set to -c.

Working with Modules

The path list contains a list of directory names in which Python looks for extension modules (Python source modules, compiled modules, or binary extensions). When you start Python, this list is initialized from a mixture of built-in rules, the contents of the PYTHONPATH environment variable, and the registry contents (on Windows). But since it’s an ordinary list, you can also manipulate it from within the program, as Example 1-67 shows.

Example 1-67. Using the sys Module to Manipulate the Module Search Path

File: sys-path-example-1.py import ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The Python 3 Standard Library by Example, Second Edition

The Python 3 Standard Library by Example, Second Edition

Doug Hellmann
Python Cookbook

Python Cookbook

Alex Martelli, David Ascher
Dive Into Python 3

Dive Into Python 3

Mark Pilgrim

Publisher Resources

ISBN: 0596000960Supplemental ContentCatalog PageErrata