您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

能否告诉python 2.7中的argparse至少需要两个参数?

能否告诉python 2.7中的argparse至少需要两个参数?

简短的答案是您不能这样做,因为nargs不支持“ 2+”之类的东西。

长答案是您可以使用以下方法解决此问题:

parser = argparse.ArgumentParser(usage='%(prog)s [-h] file file [file ...]')
parser.add_argument('file1', nargs=1, Metavar='file')
parser.add_argument('file2', nargs='+', Metavar='file', help=argparse.SUPPRESS)
namespace = parser.parse_args()
namespace.file = namespace.file1 + namespace.file2

您需要的技巧是:

上面的示例生成以下帮助字符串:

usage: test.py [-h] file file [file ...]

positional arguments:
  file

optional arguments:
  -h, --help  show this help message and exit

并且在传递少于两个参数时仍会失败:

$ python test.py arg
usage: test.py [-h] file file [file ...]
test.py: error: too few arguments
python 2022/1/1 18:48:19 有402人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶