Python: How to make an option to be required in op

2019-03-17 12:34发布

I've read this http://docs.python.org/release/2.6.2/library/optparse.html

But I'm not so clear how to make an option to be required in optparse?

I've tried to set "required=1" but I got an error:

invalid keyword arguments: required

I want to make my script require --file option to be input by users. I know that the action keyword gives you error when you don't supply value to --file whose action="store_true".

9条回答
趁早两清
2楼-- · 2019-03-17 13:31

I would use argparse library that has this functionality embedded:

PARSER.add_argument("-n", "--namespace", dest="namespace", required=True,
              help="The path within the repo to the data base")

argparse reference

查看更多
时光不老,我们不散
3楼-- · 2019-03-17 13:36

On the help message of each required variable Im writting a '[REQUIRED]' string at the beggining, to tag it to be parsed later, then I can simply use this function to wrap it around:

def checkRequiredArguments(opts, parser):
    missing_options = []
    for option in parser.option_list:
        if re.match(r'^\[REQUIRED\]', option.help) and eval('opts.' + option.dest) == None:
            missing_options.extend(option._long_opts)
    if len(missing_options) > 0:
        parser.error('Missing REQUIRED parameters: ' + str(missing_options))

parser = OptionParser()
parser.add_option("-s", "--start-date", help="[REQUIRED] Start date")
parser.add_option("-e", "--end-date", dest="endDate", help="[REQUIRED] End date")
(opts, args) = parser.parse_args(['-s', 'some-date'])
checkRequiredArguments(opts, parser)
查看更多
家丑人穷心不美
4楼-- · 2019-03-17 13:37

Since if not x doesn't work for some(negative,zero) parameters,

and to prevent lots of if tests, i preferr something like this:

required="host username password".split()

parser = OptionParser()
parser.add_option("-H", '--host', dest='host')
parser.add_option("-U", '--user', dest='username')
parser.add_option("-P", '--pass', dest='password')
parser.add_option("-s", '--ssl',  dest='ssl',help="optional usage of ssl")

(options, args) = parser.parse_args()

for r in required:
    if options.__dict__[r] is None:
        parser.error("parameter %s required"%r)
查看更多
登录 后发表回答