Noa*_*h R 2 python command-line-arguments argparse
而不是用户必须使用script.py --file c:/stuff/file.txt有一种方法让用户可选地使用--file?所以相反,它看起来像script.py c:/stuff/file.txt但解析器仍然知道用户正在引用--file参数(因为它暗示).
试试这个
import argparse
class DoNotReplaceAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if not getattr(namespace, self.dest):
            setattr(namespace, self.dest, values)
parser = argparse.ArgumentParser(description="This is an example.")
parser.add_argument('file', nargs='?', default='', help='specifies a file.', action=DoNotReplaceAction)
parser.add_argument('--file', help='specifies a file.')
args = parser.parse_args()
# check for file argument
if not args.file:
    raise Exception('Missing "file" argument')
看看帮助信息.所有参数都是可选的
usage: test.py [-h] [--file FILE] [file]
This is an example.
positional arguments:
  file         specifies a file.
optional arguments:
  -h, --help   show this help message and exit
  --file FILE  specifies a file.
需要注意的一点是,position file将覆盖optional --file并设置args.file为default''.为了克服这个问题,我使用定制action来定位file.它禁止覆盖已设置的属性.
另一件需要注意的事情是,而不是提出Exception你可以指定默认值.