简体   繁体   English

python argparse可选参数

[英]python argparse optional arguments

I am evaluating argparse for my python program and I am not sure if I can accomplish following: 我正在为我的python程序评估argparse,但不确定是否可以完成以下工作:

Usage:
prog --file <filename> --function <function name> --mode <mode name>
prog --file <filename> --function <function name>  {in this case default mode is applied on specified function in a specified file}
prog --file <filename> --mode <mode name> {in this case specified mode is applied on a specified file}

In short I want to make entire --function and it's follower optional. 简而言之,我想使整个--function及其跟随者是可选的。 Currently I have passed nargs = "?" 目前,我已经通过了nargs =“?” in that but that confuses argparse and when I pass --mode it takes it as --function. 在那种情况下,但这使argparse感到困惑,当我通过--mode时,它将其当作--function。

parser = argparse.ArgumentParser(description = "program")
parser.add_argument("file", nargs=2)
parser.add_argument("function", nargs='?')
parser.add_argument("mode", nargs='?', default='read')

Is there anyway I can accomplish this using argparse? 无论如何,我可以使用argparse完成此操作吗? Or I would have to write my own parser using sys.args ??? 否则我将不得不使用sys.args编写自己的解析器?

Thanks. 谢谢。

I found this while researching a different argparse question. 我在研究另一个argparse问题时发现了这一点。 Maybe my answer will help someone else. 也许我的回答会帮助别人。 If I understand the question, you need to add "--" to the optional arguments. 如果我理解这个问题,则需要在可选参数中添加“-”。 Declarations would look like this: 声明如下所示:

parser = argparse.ArgumentParser(description = "program")
parser.add_argument("file")
parser.add_argument("--function")
parser.add_argument("--mode", default='read')

When you do this, 'file' is required, and 'function' and 'mode' are optional. 执行此操作时,“文件”是必需的,“功能”和“模式”是可选的。
Add the following lines to your code snippet, and you will get output shown. 将以下行添加到您的代码段中,您将获得显示的输出。

args = parser.parse_args('my_file --function func_1'.split())
print (args)
Namespace(file='my_file', function='func_1', mode='read')

args = parser.parse_args('other_file --mode write'.split())
print (args)
Namespace(file='other_file', function=None, mode='write')

You can access individual values with args.file, args.function, and args.mode . 您可以使用args.file, args.function, and args.mode来访问各个值。
What you do with them is up to you. 您对他们的处理取决于您。 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM