I'm looking for a way to make a commandline option with optional argument using optparse
Python module.
For example there are two command lines: foobar -u -v
and foobar -u USERNAME -v
. While latter gets USERNAME
as an argument, former should detect absence of an argument and get username from the environment variable or by other means, and not treat -v
as an argument, but as an option instead.
I know there is possibility to take multiple arguments using append
action, but it requires at least one argument.
Are there any solutions?
UPDATE:
Why won't this script works if no arugment is provided ? I have given some value to Default also. Cannot something like this can used ?
#!/usr/bin/env python
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-u", "--user", dest="in_dir",
help="write report to FILE", action= "store", default='USERNAME')
(options, args) = parser.parse_args()
if options.in_dir == 'USERNAME':
print' argument supplied or taken from default '
else:
print 'arugment supplied'
On executing this file we get ./options.py -f Usage: options.py [options]
options.py: error: -f option requires an argument
As I have given some values in the default. Why cannot it take that value from there ? Is any there other solution to this?
Maybe you could inspect sys.argv
before adding the -u
option to your parser. If the next element on sys.argv
(following -u
) is not a username, then you could insert the username into the list before parsing. Something like the following code :
import sys
from optparse import OptionParser as OP
cmdLine = sys.argv
i = cmdLine.index('-u')
if (i+1) == len(cmdLine) or cmdLine[i+1] not in users:
cmdLine.insert(i+1,userName)
p = OP()
p.add_option('-u',action='append')
p.parse_args(cmdLine[1:])