argparse doesn't check for positional arguments

白昼怎懂夜的黑 提交于 2019-12-06 06:04:38

Your problem is that you're specifying nargs='?'. From the documentation:

'?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced.

If you leave out the nargs='?' then the argument will be required, and argparse will display an error if it is not provided. A single argument is consumed if action='store' (the default).

You can also specify nargs=1; the difference is that this produces a list containing one item, as opposed to the item itself. See the documentation for more ways you can use nargs.

Works for me.

Code:

#!/usr/bin/python

import argparse

parser=argparse.ArgumentParser(description='script to run')

parser.add_argument('inputFile', nargs='?', type=argparse.FileType('rt'))
parser.add_argument('inputString', action='store', nargs='?') 
parser.add_argument('-option1', metavar='percent', type=float, action='store')
parser.add_argument('-option2', metavar='outFile1', type=argparse.FileType('w'))
parser.add_argument('-option3', action='store', default='<10')
args = parser.parse_args()

Execution:

# ./blah.py -h
usage: blah.py [-h] [-option1 percent] [-option2 outFile1] [-option3 OPTION3]
               [inputFile] [inputString]

script to run

positional arguments:
  inputFile
  inputString

optional arguments:
  -h, --help         show this help message and exit
  -option1 percent
  -option2 outFile1
  -option3 OPTION3

Did you overlook the second line in the argument list?

It works as expected. There is no inputString if you run it as script.py inputfile (only one argument is given, but inputString is the second argument).

narg='?' means that the argument is optional (they are surrounded by [] in the help message).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!