24 Parse the command line arguments.
27 from optparse
import OptionParser, OptionValueError
29 def addOperation(option, opt, value, parser, action):
31 Append to the list of actions the tuple (action, (<args>, ...)).
33 if action
not in (
'unset',
'loadXML'):
37 raise OptionValueError(
"Invalid value for option %s: '%s', it requires NAME=VALUE." % (opt, value))
40 parser.values.actions.append((action, value))
42 parser = OptionParser(prog =
"env.py",
43 usage =
"Usage: %prog [OPTION]... [NAME=VALUE]... [COMMAND [ARG]...]",
44 description =
"Set each NAME to VALUE in the environment and run COMMAND.",
45 epilog =
"The operations are performed in the order they appear on the "
46 "command line. If no COMMAND is provided, print the resulting "
47 "environment. (Note: this command is modeled after the Unix "
48 "command 'env', see \"man env\")" )
50 parser.add_option(
"-i",
"--ignore-environment",
52 help=
"start with an empty environment")
53 parser.add_option(
"-u",
"--unset",
55 action=
"callback", callback=addOperation,
56 type=
"str", nargs=1, callback_args=(
'unset',),
57 help=
"remove variable from the environment")
58 parser.add_option(
"-s",
"--set",
60 action=
"callback", callback=addOperation,
61 type=
"str", nargs=1, callback_args=(
'set',),
62 help=
"set the variable NAME to VALUE")
63 parser.add_option(
"-a",
"--append",
65 action=
"callback", callback=addOperation,
66 type=
"str", nargs=1, callback_args=(
'append',),
67 help=
"append VALUE to the variable NAME (with a '%s' as separator)" % os.pathsep)
68 parser.add_option(
"-p",
"--prepend",
70 action=
"callback", callback=addOperation,
71 type=
"str", nargs=1, callback_args=(
'prepend',),
72 help=
"prepend VALUE to the variable NAME (with a '%s' as separator)" % os.pathsep)
73 parser.add_option(
"-x",
"--xml",
74 action=
"callback", callback=addOperation,
75 type=
"str", nargs=1, callback_args=(
'loadXML',),
76 help=
"XML file describing the changes to the environment")
77 parser.add_option(
"--sh",
78 action=
"store_const", const=
"sh", dest=
"shell",
79 help=
"Print the environment as shell commands for 'sh'-derived shells.")
80 parser.add_option(
"--csh",
81 action=
"store_const", const=
"csh", dest=
"shell",
82 help=
"Print the environment as shell commands for 'csh'-derived shells.")
83 parser.add_option(
"--py",
84 action=
"store_const", const=
"py", dest=
"shell",
85 help=
"Print the environment as Python dictionary.")
86 parser.disable_interspersed_args()
87 parser.set_defaults(actions=[], ignore_environment=
False)
89 return parser.parse_args()