如何使用argparse在python中添加多个参数选项? [英] how to add multiple argument options in python using argparse?

查看:963
本文介绍了如何使用argparse在python中添加多个参数选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求:

现在,当我使用此命令运行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,该参数将确定要保存的filpath和名称.我该怎么做.处理或组合多个选项的最佳方法是什么.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆