Getopt: Using Environment Var To Override

Skip Montanaro skip at pobox.com
Sat Jan 4 02:51:07 CET 2003


    Tim> I currently use getopt to process my command line args.  Is there
    Tim> some standard/easy/idiomatic/Pythonic way to supplement this with
    Tim> an environment variable?  

None that I'm aware of, however depending on how your environment variable
is formatted it might be trivial tack it onto the front or back of the args
you pass to getopt.  Suppose you require your environment variable value to
look like a set of arguments.  It could be as simple as

    envargs = os.environ.get("MYENV")
    if envargs is not None:
        opts, args = getopt.getopt(envargs.split(), ...)
    for opt, arg in opts:
        ...

    if args:
        handle error?

then later,

    opts, args = getopt.getopt(sys.argv[1:], ...)
    for opt, arg in opts:
        ...

    if args:
        process parameters

(Based upon the 1, 2, 3 you gave, I think you want to process environment
variables before the command line.)

Skip





More information about the Python-list mailing list