Getopt: Using Environment Var To Override
Tim Daneliuk
tundra at tundraware.com
Sat Jan 4 14:00:07 EST 2003
Skip Montanaro wrote:
> 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
>
In case anyone else cares, here's what I ended up with -
I use the program name (PROGNAME) as the environment
variable to hold the options in the same format as one
would use on the command line:
--------------------------------------------------------
# Command line processing - Process any options set in the
# environment first, and then those given on the command line
OPTIONS = sys.argv[1:]
envopt = os.getenv(PROGNAME.upper())
if envopt:
OPTIONS = envopt.split() + OPTIONS
try:
opts, args = getopt.getopt(OPTIONS, 'your options go here')
except getopt.GetoptError:
Usage()
sys.exit(1)
--
------------------------------------------------------------------------------
Tim Daneliuk
tundra at tundraware.com
More information about the Python-list
mailing list