这是我要做的:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--dry-run', action='store_true')
parser.add_argument('input_file', type=argparse.FileType('r'))
parser.add_argument('servername', nargs='?')
args = parser.parse_args()
if args.servername is None and not args.dry_run:
parser.error("Option 'servername' is required when not in dry-run mode.")
print args
例子:
$ ./prog.py inputfile servername
Namespace(dry_run=False, input_file=<open file 'inputfile', mode 'r' at 0x283440>, servername='servername')
$ ./prog.py inputfile -d
Namespace(dry_run=True, input_file=<open file 'inputfile', mode 'r' at 0x2cf440>, servername=None)
$ ./prog.py -d inputfile servername
Namespace(dry_run=True, input_file=<open file 'inputfile', mode 'r' at 0x1f4440>, servername='servername')
$ ./prog.py inputfile
usage: prog.py [-h] [-d] input_file [servername]
prog.py: error: Option 'servername' is required when not in dry-run mode.
您也可以使用自定义操作来执行此操作,它具有相同的效果:
class ServernameAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if values is None and not namespace.dry_run:
parser.error("Option 'servername' is required when not in dry-run mode.")
setattr(namespace, self.dest, values)
...
parser.add_argument('servername', nargs='?', action=ServernameAction)
...