简单的argparse示例需要:1个参数,3个结果

本文翻译自:Simple argparse example wanted: 1 argument, 3 results

The documentation for the argparse python module , while excellent I'm sure, is too much for my tiny beginner brain to grasp right now. argparse python模块文档虽然非常好,但我确信,对于我的小初学者大脑来说,这个文档太多了。 I don't need to do math on the command line or meddle with formatting lines on the screen or change option characters. 我不需要在命令行上进行数学运算,也不需要在屏幕上使用格式化线条或更改选项字符。 All I want to do is "If arg is A, do this, if B do that, if none of the above show help and quit" . 我想要做的就是“如果arg是A,那么,如果B这样做,如果以上都不显示帮助并退出”


#1楼

参考:https://stackoom.com/question/VA7x/简单的argparse示例需要-个参数-个结果


#2楼

Matt is asking about positional parameters in argparse, and I agree that the Python documentation is lacking on this aspect. Matt询问argparse中的位置参数,我同意Python文档在这方面缺乏。 There's not a single, complete example in the ~20 odd pages that shows both parsing and using positional parameters . 在大约20个奇数页面中没有一个完整的例子显示解析和使用位置参数

None of the other answers here show a complete example of positional parameters, either, so here's a complete example: 这里没有其他答案显示位置参数的完整示例,所以这是一个完整的例子:

# tested with python 2.7.1
import argparse

parser = argparse.ArgumentParser(description="An argparse example")

parser.add_argument('action', help='The action to take (e.g. install, remove, etc.)')
parser.add_argument('foo-bar', help='Hyphens are cumbersome in positional arguments')

args = parser.parse_args()

if args.action == "install":
    print("You asked for installation")
else:
    print("You asked for something other than installation")

# The following do not work:
# print(args.foo-bar)
# print(args.foo_bar)

# But this works:
print(getattr(args, 'foo-bar'))

The thing that threw me off is that argparse will convert the named argument "--foo-bar" into "foo_bar", but a positional parameter named "foo-bar" stays as "foo-bar", making it less obvious how to use it in your program. 让我失望的是,argparse会将命名参数“--foo-bar”转换为“foo_bar”,但名为“foo-bar”的位置参数会保留为“foo-bar”,这使得它不太明显如何在你的程序中使用它。

Notice the two lines near the end of my example -- neither of those will work to get the value of the foo-bar positional param. 注意我示例末尾附近的两行 - 这些行都不能用于获取foo-bar位置参数的值。 The first one is obviously wrong (it's an arithmetic expression args.foo minus bar), but the second one doesn't work either: 第一个显然是错误的(它是一个算术表达式args.foo减去bar),但第二个也不起作用:

AttributeError: 'Namespace' object has no attribute 'foo_bar'

If you want to use the foo-bar attribute, you must use getattr , as seen in the last line of my example. 如果要使用foo-bar属性,则必须使用getattr ,如我的示例的最后一行所示。 What's crazy is that if you tried to use dest=foo_bar to change the property name to something that's easier to access, you'd get a really bizarre error message: 令人抓狂的是,如果您尝试使用dest=foo_bar将属性名称更改为更容易访问的内容,则会收到一条非常奇怪的错误消息:

ValueError: dest supplied twice for positional argument

Here's how the example above runs: 以下是上述示例的运行方式:

$ python test.py
usage: test.py [-h] action foo-bar
test.py: error: too few arguments

$ python test.py -h
usage: test.py [-h] action foo-bar

An argparse example

positional arguments:
  action      The action to take (e.g. install, remove, etc.)
  foo-bar     Hyphens are cumbersome in positional arguments

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

$ python test.py install foo
You asked for installation
foo

#3楼

To add to what others have stated: 添加其他人所说的内容:

I usually like to use the 'dest' parameter to specify a variable name and then use 'globals().update()' to put those variables in the global namespace. 我通常喜欢使用'dest'参数来指定变量名,然后使用'globals()。update()'将这些变量放在全局命名空间中。

Usage: 用法:

$ python script.py -i "Hello, World!"

Code: 码:

...
parser.add_argument('-i', '--input', ..., dest='inputted_variable',...)
globals().update(vars(parser.parse_args()))
...
print(inputted_variable) # Prints "Hello, World!"

#4楼

My understanding of the original question is two-fold. 我对原始问题的理解是双重的。 First, in terms of the simplest possible argparse example, I'm surprised that I haven't seen it here. 首先,就最简单的argparse示例而言,我很惊讶我在这里没有看到它。 Of course, to be dead-simple, it's also all overhead with little power, but it might get you started. 当然,简单来说,它也是所有开销,但功率很小,但它可能会让你开始。

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("a")
args = parser.parse_args()

if args.a == 'magic.name':
    print 'You nailed it!'

But this positional argument is now required. 但现在需要这种位置论证。 If you leave it out when invoking this program, you'll get an error about missing arguments. 如果在调用此程序时将其遗漏,则会收到有关缺少参数的错误。 This leads me to the second part of the original question. 这引出了我原始问题的第二部分。 Matt Wilkie seems to want a single optional argument without a named label (the --option labels). Matt Wilkie似乎想要一个没有命名标签的可选参数( - 选项标签)。 My suggestion would be to modify the code above as follows: 我的建议是修改上面的代码如下:

...
parser.add_argument("a", nargs='?', default="check_string_for_empty")
...
if args.a == 'check_string_for_empty':
    print 'I can tell that no argument was given and I can deal with that here.'
elif args.a == 'magic.name':
    print 'You nailed it!'
else:
    print args.a

There may well be a more elegant solution, but this works and is minimalist. 可能有一个更优雅的解决方案,但这是有效的,是极简主义的。


#5楼

Note the Argparse Tutorial in Python HOWTOs . 请注意Python HOWTO中Argparse教程 It starts from most basic examples, like this one: 它从大多数基本示例开始,如下所示:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
args = parser.parse_args()
print(args.square**2)

and progresses to less basic ones. 并发展到不太基本的。

There is an example with predefined choice for an option, like what is asked: 有一个示例可以选择预定义的选项,例如:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
    print("{}^2 == {}".format(args.square, answer))
else:
    print(answer)

#6楼

Here's what I came up with in my learning project thanks mainly to @DMH... 这是我在学习项目中提出的,主要归功于@DMH ......

Demo code: 演示代码:

import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--flag', action='store_true', default=False)  # can 'store_false' for no-xxx flags
    parser.add_argument('-r', '--reqd', required=True)
    parser.add_argument('-o', '--opt', default='fallback')
    parser.add_argument('arg', nargs='*') # use '+' for 1 or more args (instead of 0 or more)
    parsed = parser.parse_args()
    # NOTE: args with '-' have it replaced with '_'
    print('Result:',  vars(parsed))
    print('parsed.reqd:', parsed.reqd)

if __name__ == "__main__":
    main()

This may have evolved and is available online: command-line.py 这可能已经发展并可在线获得: command-line.py

Script to give this code a workout: command-line-demo.sh 编写此代码的脚本: command-line-demo.sh

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,让我来回答你的问题。 首先,argparsePython的一个命令行参数解析库,它可以让我们方便地处理命令行参数。使用argparse,我们可以轻松定义命令行参数,同时还能为这些参数添加一些说明和默认值。 关于你的问题,我们可以通过定义两个互斥的参数来解决。具体来说,我们可以使用argparse库中的add_mutually_exclusive_group()方法来创建一个互斥的参数组,然后将需要互斥的两个参数添加到这个组中即可。 下面是一个使用argparse定义5个参数,并且其中两个参数的互斥关系的示例代码: ```python import argparse parser = argparse.ArgumentParser(description='An example of using argparse to parse command-line arguments') # 创建一个互斥参数组 group = parser.add_mutually_exclusive_group() # 添加5个参数 parser.add_argument('--arg1', type=str, help='argument 1') parser.add_argument('--arg2', type=int, help='argument 2') parser.add_argument('--arg3', type=float, help='argument 3') parser.add_argument('--arg4', action='store_true', help='argument 4') parser.add_argument('--arg5', action='store_true', help='argument 5') # 将需要互斥的两个参数添加到同一组中 group.add_argument('--arg4', action='store_true', help='argument 4') group.add_argument('--arg5', action='store_true', help='argument 5') # 解析命令行参数 args = parser.parse_args() # 打印参数值 print(args.arg1) print(args.arg2) print(args.arg3) print(args.arg4) print(args.arg5) ``` 在上面的代码中,我们首先创建了一个ArgumentParser对象,并设置了一个描述信息。然后,我们使用add_argument()方法添加了5个参数,其中两个参数(arg4和arg5)被添加到了同一个互斥的参数组中。 最后,我们使用parse_args()方法解析命令行参数,并打印了各个参数的值。 希望这个示例对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值