如何使用argparse在python中添加多个参数选项? [英] how to add multiple argument options in python using argparse?
问题描述
我的要求:
现在当我用这个命令运行我的 python 应用程序时
For now when I run my python application with this command
python main.py -d listhere/users.txt
程序将运行并将结果文件保存为预定义的名称,例如 reports.txt
The program will run and save the result file as predefined name say reports.txt
现在我想添加此功能以允许用户选择放置文件名的内容以及保存位置
Now I want to add this functionality to allow users to choose what to put the filename and where to save as so
python main.py -d -o output/newfilname -i listhere/users.txt
一切都一样,但我想传递另一个参数 -o 来确定要保存的文件路径和名称.我该怎么做.处理或组合多个选项的最佳方式是什么.
Everything is same but I want another argument -o to be passed which will determine the filpath and name to be saved. How do I do it. What is the best way to handle or combine multiple options.
我试过了
parser = argparse.ArgumentParser(description = "CHECK-ACCESS REPORTING.")
parser.add_argument('--user','-d', nargs='?')
parser.add_argument('--output','-d -o', nargs='?')
parser.add_argument('--input','-i', nargs='?')
args = parser.parse_args(sys.argv[1:])
if args.output and args.input:
#operation that involves output filename too
elif args.user and not args.input:
#default operation only
else:
#notset
尝试以这种方式解决问题时出现此错误
I am getting this error when trying to solve the issue this way
错误:
report.py:错误:无法识别的参数:-o listhere/users.txt
推荐答案
nargs='?'
标记选项有 3 种方式
A nargs='?'
flagged option works in 3 ways
parser.add_argument('-d', nargs='?', default='DEF', const='CONST')
命令行:
foo.py -d value # => args.d == 'value'
foo.py -d # => args.d == 'CONST'
foo.py # => args.d == 'DEF'
https://docs.python.org/3/library/argparse.html#const
利用这一点,您不应该需要像这样错误的 -d -o
标志.
Taking advantage of that, you shouldn't need anything like this erroneous -d -o
flag.
如果不使用const
参数,就不要使用'?'
If you don't use the const
parameter, don't use '?'
parser.add_argument('--user','-u', nargs='?', const='CONST', default='default_user')
parser.add_argument('--output','-o', default='default_outfile')
parser.add_argument('--input','-i', default='default_infile')
这篇关于如何使用argparse在python中添加多个参数选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!