python使用argparse.ArgumentParser方法

cae*_*sar 17 python command-line argparse

我试图学习如何argparse.ArgumentParser工作,我为此写了几行:

global firstProduct
global secondProduct 
myparser=argparse.ArgumentParser(description='parser test')
myparser.add_argument("product1",help="enter product1",dest='product_1')
myparser.add_argument("product2",help="enter product2",dest='product_2')

args=myparser.parse_args()

firstProduct=args.product_1
secondProduct=args.product_2
Run Code Online (Sandbox Code Playgroud)

我只是想,当用户运行此脚本有两个参数我的代码并将其分配给firstProductsecondProduct分别.但它不起作用.有人告诉我为什么吗?提前致谢

unu*_*tbu 17

dest使用位置参数时省略参数.为位置参数提供的名称将是参数的名称:

import argparse
myparser = argparse.ArgumentParser(description='parser test')
myparser.add_argument("product_1", help="enter product1")
myparser.add_argument("product_2", help="enter product2")

args = myparser.parse_args()
firstProduct = args.product_1
secondProduct = args.product_2
print(firstProduct, secondProduct)
Run Code Online (Sandbox Code Playgroud)

运行% test.py foo bar打印

('foo', 'bar')
Run Code Online (Sandbox Code Playgroud)

  • (1)如果指定带单引号或双引号的字符串,则结果没有区别.有这两个选项只会引用引号:`"'"`或`'"'`例如.(2)当`add_argument`的第一个参数以`-`或`--`开头时,它是一个可选参数没有破折号,它是一个位置参数.位置参数由它们的位置识别:`test.py foo bar`将foo解释为处于第一个位置,因此它与第一个位置参数"product_1"相关联. (4认同)
  • `dest`参数可以与`optionals`一起使用(以`-`开头) (3认同)
  • 对我来说看起来是个错误的奇怪行为。如果我在位置参数名称中使用字符 '-',形成示例 `'my-name'` 它看起来不会被更改为 dest,其中 '-' 替换为 '_' ;因为它不能显式地使用`'dest'` 参数,所以无法访问该值!如果我使用 str() 转储返回的 `'args'`,我会得到一些谎言 `Namespace( ... , my-name=1, ....)` 但我不会让 python 接受这样的一个变量!其实是语法错误写`args.my-name=xxxx` (2认同)

vil*_*laa 11

除了unutbu的答案之外,您还可以使用该metavar属性以使目标变量和帮助菜单中显示的变量名称不同,如此链接所示.

例如,如果你这样做:

myparser.add_argument("firstProduct", metavar="product_1", help="enter product1")
Run Code Online (Sandbox Code Playgroud)

您可以使用该参数,args.firstProduct但将其列product_1在帮助中.