Linux/Unix > Python Essential Reference, Second Edition > 9. Input and Output > Reading Options and Environment Variables | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105084124000125051049191

### Reading Options and Environment Variables

When the interpreter starts, command-line options are placed in the list `sys.argv`. The first element is the name of the program. Subsequent elements are the options presented on the command line after the program name. The following program shows how to access command-line options:

    # printopt.py
    # Print all of the command-line options
    import sys
    for i in range(len(sys.argv)):
        print "sys.argv[%d] = %s" % (i, sys.argv[i])

Running the program produces the following:

    % python printopt.py foo bar -p
    sys.argv[0] = printopt.py
    sys.argv[1] = foo
    sys.argv[2] = bar
    sys.argv[3] = -p
    %

Environment variables are accessed in the dictionary `os.environ`. For example:

    import os
    path = os.environ["PATH"]
    user = os.environ["USER"]
    editor = os.environ["EDITOR"]
    ... etc ...

To modify the environment variables, set the `os.environ` variable. Alternatively, you can use the `os.putenv()` function. For example:

    os.environ["FOO"] = "BAR"
    os.putenv("FOO","BAR")

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.