【问题标题】:Simple argparse example wanted: 1 argument, 3 results需要简单的 argparse 示例:1 个参数,3 个结果
【发布时间】:2011-11-17 15:10:23
【问题描述】:

argparse python module 对应的documentation 虽然我敢肯定,但对于我的小初学者来说,现在已经无法掌握。我不需要在命令行上进行数学运算,也不需要干预屏幕上的格式行或更改选项字符。我想要做的只是“如果 arg 是 A,则执行此操作,如果 B 执行此操作,如果以上都没有显示帮助并退出”

【问题讨论】:

  • 然后只需检查sys.argv 以获得您想要的参数...
  • 试过plac吗?这是一个易于使用的 argparse 包装器,带有 great documentation
  • 不是你。它是 argparse。它试图带你踏上星际之旅,并不关心你要去哪里。
  • 又是疯狂的“pythonic” API:/
  • 祝福你 matt wilkie,为无处不在的小初学者挺身而出。

标签: python argparse


【解决方案1】:

这是我使用argparse(带有多个参数)的方式:

parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
parser.add_argument('-b','--bar', help='Description for bar argument', required=True)
args = vars(parser.parse_args())

args 将是一个包含参数的字典:

if args['foo'] == 'Hello':
    # code here

if args['bar'] == 'World':
    # code here

在您的情况下,只需添加一个参数。

【讨论】:

  • 正如我在对另一个答案的评论中提到的,我想保留 argparse 的自动帮助格式,但似乎没有选项可以有一个未命名的参数(更有可能我只是不'当我看到它时不明白),例如需要做foo.py --action installfoo.py --action remove 而不是简单的foo.py install
  • @mattwilkie 然后你必须像这样定义一个位置参数:parser.add_argument('install', help='Install the app')(注意你不能用required=True定义一个位置参数)
  • 作为 argparse 的菜鸟,这个答案确实很有帮助,因为 我不知道在通过选项后在哪里可以找到它们。换句话说,我需要了解上面的args dict 是如何生成的。
  • 直接从命令行调用程序时使用“短格式”,在脚本中运行程序/命令时使用“长格式”。在这种情况下,长格式更易于人类阅读,因此更容易遵循代码/脚本的逻辑。
  • 我个人觉得以args.fooargs.bar 的形式访问参数而不是字典语法更简洁。当然,无论哪种方式都可以,但 args 实际上不是字典,而是 argparse.Namespace 对象。
【解决方案2】:

我对原始问题的理解是双重的。首先,就最简单的 argparse 示例而言,我很惊讶我在这里没有看到它。当然,为了简单起见,这也是开销,而且功率很小,但它可能会让你开始。

import argparse

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

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

但是现在需要这个位置参数。如果你在调用这个程序时忽略它,你会得到一个关于缺少参数的错误。这导致我进入原始问题的第二部分。 Matt Wilkie 似乎想要一个没有命名标签(--option 标签)的单个 optional 参数。我的建议是修改上面的代码如下:

...
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

很可能有一个更优雅的解决方案,但这很有效并且是极简的。

【讨论】:

  • 经过一段时间的思考,我得出结论,这个问题实际上最好地回答了所问的问题以及我当时所处的困境。其他优秀的答案已经获得了足够多的代表来证明它们的价值,并且可以经受住一点竞争。 :-)
  • @badnack:这就是你想要的,无论'a'代表什么。如果您期望一个参数,例如文件名,它就是在命令行中输入的文件名。然后您可以自己处理以确定它是否存在于文件系统中,但这是另一个问答。
  • @mightypile 你能告诉我什么时候“位置参数”有用吗?我在我的代码中添加了类似parser.add_argument('n', nargs='?', default=5) 的内容,当我运行python3 test.py n 3 时,出现此错误:usage: test.py [-h] [n] test.py: error: unrecognized arguments: 3 提前谢谢!
  • @Milan 在其给定位置需要位置参数,并且在调用时不需要显式命名,因为它是必需的/预期的/位置的(即test.py 3)。您创建了一个带有单个 optional 参数(并且没有位置参数)的脚本,并且正如预期的那样,它读取“n”作为名为“n”的第一个参数(所以args.n == "n")并且不知道什么与“3”有关。见the docs
  • @mightypile 我明白了……现在我明白了。非常感谢您抽出宝贵的时间并回复:)
【解决方案3】:

argparse 文档相当不错,但遗漏了一些可能不明显的有用细节。 (@Diego Navarro 已经提到了其中的一些,但我会尝试稍微扩展他的答案。)基本用法如下:

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--my-foo', default='foobar')
parser.add_argument('-b', '--bar-value', default=3.14)
args = parser.parse_args()

您从parse_args() 返回的对象是一个“命名空间”对象:其成员变量以您的命令行参数命名的对象。 Namespace 对象是您访问参数以及与它们关联的值的方式:

args = parser.parse_args()
print (args.my_foo)
print (args.bar_value)

(请注意,argparse 在命名变量时将参数名称中的“-”替换为下划线。)

在许多情况下,您可能希望将参数简单地用作没有值的标志。您可以像这样在 argparse 中添加它们:

parser.add_argument('--foo', action='store_true')
parser.add_argument('--no-foo', action='store_false')

上面将分别创建名为 'foo' 且值为 True 的变量和名为 'no_foo' 的值为 False 的变量:

if (args.foo):
    print ("foo is true")

if (args.no_foo is False):
    print ("nofoo is false")

另请注意,您可以在添加参数时使用“必需”选项:

parser.add_argument('-o', '--output', required=True)

这样,如果您在命令行中省略此参数 argparse 将告诉您它丢失并停止执行您的脚本。

最后,请注意,可以使用 vars 函数创建参数的 dict 结构,如果这样可以让您的生活更轻松。

args = parser.parse_args()
argsdict = vars(args)
print (argsdict['my_foo'])
print (argsdict['bar_value'])

如您所见,vars 返回一个 dict,其中您的参数名称作为键,它们的值作为值。

还有很多其他选项和您可以做的事情,但这应该涵盖最基本、最常见的使用场景。

【讨论】:

  • '-f''-b' 的意义何在?为什么不能省略这个?
  • 每个运行时选项都有一个“短格式”(一个破折号)和“长格式”(两个破折号)版本是非常常规的。例如,您会在几乎所有标准的 Unix/Linux 实用程序中看到这一点;做一个man cpman ls,你会发现很多选项都有两种口味(例如-f, --force)。人们喜欢其中一种的原因可能多种多样,但无论如何,在您的程序中同时使用这两种形式是非常标准的。
  • @DMH 为什么print(args.my_foo) 有效但print(args.f) 给出错误:AttributeError: 'Namespace' object has no attribute 'f'?另一方面,在add_argument 中,如果我没有指定命名标签(--option 标签),即parser.add_argument('-f', default='foobar'),那么我可以运行print(args.f)。为什么?提前谢谢!
【解决方案4】:

Matt 询问 argparse 中的位置参数,我同意 Python 文档在这方面缺乏。在大约 20 个页面中没有一个完整的示例同时显示解析和使用位置参数

这里的其他答案都没有显示位置参数的完整示例,所以这里有一个完整的示例:

# 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'))

让我失望的是 argparse 会将命名参数“--foo-bar”转换为“foo_bar”,但是名为“foo-bar”的位置参数保持为“foo-bar”,使其更少很明显如何在你的程序中使用它。

请注意我的示例末尾附近的两行 - 这两行都无法获取 foo-bar 位置参数的值。第一个显然是错误的(它是一个算术表达式 args.foo 减去 bar),但第二个也不起作用:

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

如果要使用foo-bar 属性,则必须使用getattr,如我示例的最后一行所示。疯狂的是,如果您尝试使用 dest=foo_bar 将属性名称更改为更易于访问的名称,您会收到一条非常奇怪的错误消息:

ValueError: dest supplied twice for positional argument

上面的例子是这样运行的:

$ 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

【讨论】:

  • nargs='?'stackoverflow.com/questions/4480075/… 中“可选位置”的咒语
  • 位置foo-bar 未转换为foo_bar 的事实在bugs.python.org/issue15125 中得到解决。
  • 我认为这个错误的一个更简单的解决方法是只调用参数“foo_bar”而不是“foo-bar”,然后print args.foo_bar 工作。由于它是一个位置参数,因此您不必在调用脚本时指定名称,因此对用户而言并不重要。
  • @luator 你说得对,重命名参数很容易,但错误报告的作者很好地证明了这仍然是一个错误功能,因为不必要的认知负担。使用 argparse 时,必须暂停并回忆选项和参数的不同命名约定。见bugs.python.org/msg164968
  • @mehaase 我完全同意这是一个应该修复的错误功能。我只是认为重命名参数比必须使用getattr 更容易且更少混淆(它也更灵活,因为它允许您将参数从可选更改为位置,而无需更改使用该值的代码)。
【解决方案5】:

另一个摘要介绍,灵感来自this post

import argparse

# define functions, classes, etc.

# executes when your script is called from the command-line
if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    #
    # define each option with: parser.add_argument
    #
    args = parser.parse_args() # automatically looks at sys.argv
    #
    # access results with: args.argumentName
    #

参数由以下组合定义:

parser.add_argument( 'name', options... )              # positional argument
parser.add_argument( '-x', options... )                # single-char flag
parser.add_argument( '-x', '--long-name', options... ) # flag with long name

常见的选项有:

  • help:使用 --help 时此参数的描述。
  • default:省略 arg 时的默认值。
  • type:如果您期望 floatint(否则为 str)。
  • dest:为标志指定不同的名称(例如 '-x', '--long-name', dest='longName')。
    注意:默认情况下,--long-name 使用 args.long_name 访问
  • action:用于对某些参数的特殊处理
    • store_true, store_false: 用于布尔参数
      '--foo', action='store_true' => args.foo == True
    • store_const: 与选项const一起使用
      '--foo', action='store_const', const=42 => args.foo == 42
    • count: 用于重复选项,如./myscript.py -vv
      '-v', action='count' => args.v == 2
    • append: 用于重复选项,如./myscript.py --foo 1 --foo 2
      '--foo', action='append' => args.foo == ['1', '2']
  • required: 如果需要标志,或者不需要位置参数。
  • nargs: 用于捕获 N 个参数的标志
    ./myscript.py --foo a b => args.foo = ['a', 'b']
  • choices:限制可能的输入(指定为字符串列表,如果type=int,则指定为整数)。

【讨论】:

    【解决方案6】:

    注意Python HOWTOs 中的Argparse Tutorial。它从最基本的示例开始,例如:

    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)
    

    然后逐渐发展到不那么基本的。

    有一个预定义选项的示例,例如询问的内容:

    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)
    

    【讨论】:

    • 很高兴看到文档已更新。我向你保证,当 OP 5 年前发布这个问题时,情况并非如此。
    【解决方案7】:

    这是我在学习项目中提出的主要感谢@DMH...

    演示代码:

    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()
    

    这可能已经发展并可以在线获得:command-line.py

    测试此代码的脚本:command-line-demo.sh

    【讨论】:

    • 最后是一个有意义的 argparse 示例
    【解决方案8】:

    代码文件:argparseDemo.py

    简单:常见情况

    • 姓名(缩写,完整),在帮助下
      import argparse
      
      argParser = argparse.ArgumentParser()
      argParser.add_argument("-n", "--name", help="your name")
      
      args = argParser.parse_args()
      print("args=%s" % args)
      
      print("args.name=%s" % args.name)
      
      • 呼叫
        • python argparseDemo.py -n Crifan
        • python argparseDemo.py --name Crifan
      • 输出:args=Namespace(name='Crifan')args.name=Crifan
    • 类型
      argParser.add_argument("-a", "--age", type=int, help="your current age")
      print("type(args.age)=%s" % type(args.age))
      
      • 电话:python argparseDemo.py --age 30
      • 输出:type(args.age)=<class 'int'>args.age=30
    • 需要
      argParser.add_argument("-a", "--age", required=True, type=int, help="your current age")
      
      • 电话:python argparseDemo.py
      • 输出:错误argparseDemo.py: error: the following arguments are required: -a/--age
    • 默认
      argParser.add_argument("-a", "--age", type=int, default=20, help="your current age. Default is 20")
      
      • 电话:python argparseDemo.py
      • 输出:args.age=20
    • 选择
      argParser.add_argument("-f", "--love-fruit", choices=['apple', 'orange', 'banana'], help="your love fruits")
      
      • 电话:python argparseDemo.py -f apple
      • 输出:args=Namespace(love_fruit='apple')args.love_fruit=apple
    • 多参数
      argParser.add_argument("-f", "--love-fruit", nargs=2, help="your love fruits")
      
      • 电话:python argparseDemo.py -f apple orange
      • 输出:args.love_fruit=['apple', 'orange']

    详情

    最简单的:-x

    • 代码:

      import argparse
      
      argParser = argparse.ArgumentParser()
      argParser.add_argument("-a") # most simple -> got args.a, type is `str`
      args = argParser.parse_args()
      
      print("args.a=%s" % args.a)
      
    • 用法 = 在命令行中运行

      python argparseDemo.py -a 30
      
      • 或:./argparseDemo.py -a 30
        • 确保argparseDemo.py 是可执行的
          • 如果没有,请添加:chmod +x argparseDemo.py
    • 输出

      args.a=30
      
    • 注意

      • 默认类型为str
        • argParser.add_argument("-a") == argParser.add_argument("-a", type=str)
        • print("type(args.a)=%s" % type(args.a)) -> type(args.a)=<class 'str'>
      • args 类型为 Namespace
        • print("type(args)=%s" % type(args)) -> type(args)=<class 'argparse.Namespace'>
      • args 值为 Namespace(a='30')
        • print("args=%s" % args) -> args=Namespace(a='30')
        • 所以我们可以打电话/使用args.a

    参数名称

    参数全名:--xxx

    • 代码
      argParser.add_argument("-a", "--age")
      
    • 用法
      • python argparseDemo.py -a 30
        • 或:python argparseDemo.py --age 30
    • 获取解析值:args.age
      • 注意:不存在 args.a不存在 args.a

    包含多个单词的完整参数名称:--xxx-yyy

    • 代码
      argParser.add_argument("-a", "--current-age")
      
    • 获取解析值:args.current_age

    添加帮助说明:help

    • 代码
      argParser.add_argument("-a", help="your age") # with help
      
    • 输出
      • 使用--help可以看说明
         python argparseDemo.py --help
        usage: argparseDemo.py [-h] [-a A]
        
        optional arguments:
        -h, --help  show this help message and exit
        -a A        your age
        

    指定参数类型:type

    • 代码
      argParser.add_argument("-a", type=int) # parsed arg is `int`, not default `str`
      
    • 输出
      • print("type(args.a)=%s" % type(args.a)) -> type(args.a)=<class 'int'>
      • print("args=%s" % args) -> args=Namespace(a=30)

    添加默认值:default

    • 代码
      argParser.add_argument("-a", type=int, default=20) # if not pass a, a use default value: 20
      
    • 效果
      • 用法:python argparseDemo.py
      • 输出:print("args.age=%s" % args.age) -> args=Namespace(a=20)

    【讨论】:

      【解决方案9】:

      您也可以使用placargparse 的包装)。

      作为奖励,它会生成简洁的帮助说明 - 见下文。

      示例脚本:

      #!/usr/bin/env python3
      def main(
          arg: ('Argument with two possible values', 'positional', None, None, ['A', 'B'])
      ):
          """General help for application"""
          if arg == 'A':
              print("Argument has value A")
          elif arg == 'B':
              print("Argument has value B")
      
      if __name__ == '__main__':
          import plac
          plac.call(main)
      

      示例输出:

      没有提供参数 - example.py:

      usage: example.py [-h] {A,B}
      example.py: error: the following arguments are required: arg
      

      提供了意外的参数 - example.py C:

      usage: example.py [-h] {A,B}
      example.py: error: argument arg: invalid choice: 'C' (choose from 'A', 'B')
      

      提供了正确的参数 - example.py A :

      Argument has value A
      

      完整的帮助菜单(自动生成)- example.py -h:

      usage: example.py [-h] {A,B}
      
      General help for application
      
      positional arguments:
        {A,B}       Argument with two possible values
      
      optional arguments:
        -h, --help  show this help message and exit
      

      简短说明:

      参数名称通常等于参数名称 (arg)。

      arg参数后面的元组注解含义如下:

      • 说明 (Argument with two possible values)
      • 参数类型 - “标志”、“选项”或“位置”之一 (positional)
      • 缩写 (None)
      • 参数值的类型 - 例如。浮点数、字符串 (None)
      • 有限的选择集 (['A', 'B'])

      文档:

      要了解有关使用 plac 的更多信息,请查看其出色的文档:

      Plac: Parsing the Command Line the Easy Way

      【讨论】:

        【解决方案10】:

        补充其他人所说的:

        我通常喜欢使用 'dest' 参数指定变量名,然后使用 'globals().update()' 将这些变量放入全局命名空间中。

        用法:

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

        代码:

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

        【讨论】:

        • 在内部 argparse 使用 getattrsetattr 访问命名空间中的值。这样它就不会被奇怪的dest 值所困扰。
        【解决方案11】:

        我浏览了所有示例和答案,但在某种程度上,它们并没有满足我的需求。所以我会给她列出一个我需要更多帮助的场景,我希望这可以更多地解释这个想法。

        最初的问题

        我需要开发一个工具来获取文件来处理它,它需要一些可选的配置文件来配置工具。

        所以我需要的是类似下面的东西

        mytool.py file.text -config config-file.json
        

        解决方案

        这里是解决方案代码

        import argparse
        
        def main():
            parser = argparse.ArgumentParser(description='This example for a tool to process a file and configure the tool using a config file.')
            parser.add_argument('filename', help="Input file either text, image or video")
            # parser.add_argument('config_file', help="a JSON file to load the initial configuration ")
            # parser.add_argument('-c', '--config_file', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)
            parser.add_argument('-c', '--config', default='configFile.json', dest='config_file', help="a JSON file to load the initial configuration " )
            parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )
        
            args = parser.parse_args()
            
            filename = args.filename
            configfile = args.config_file
        
            print("The file to be processed is", filename)
            print("The config file is", configfile)
        
            if args.debug:
                print("Debug mode enabled")
            else:
                print("Debug mode disabled")
        
            print("and all arguments are: ", args)
        
        if __name__ == '__main__':
            main()
        

        我将在多个增强中展示解决方案以展示想法

        第一轮:列出论据

        将所有输入列为强制输入,因此第二个参数将是

        parser.add_argument('config_file', help="a JSON file to load the initial configuration ")
        

        当我们获得此工具的帮助命令时,我们会发现以下结果

        (base) > python .\argparser_example.py -h
        usage: argparser_example.py [-h] filename config_file
        
        This example for a tool to process a file and configure the tool using a config file.
        
        positional arguments:
          filename     Input file either text, image or video
          config_file  a JSON file to load the initial configuration
        
        optional arguments:
          -h, --help   show this help message and exit
        

        当我如下执行时

        (base) > python .\argparser_example.py filename.txt configfile.json
        

        结果是

        The file to be processed is filename.txt
        The config file is configfile.json
        and all arguments are:  Namespace(config_file='configfile.json', filename='filename.txt')
        

        但配置文件应该是可选的,我从参数中删除了它

        (base) > python .\argparser_example.py filename.txt
        

        结果将是:

        usage: argparser_example.py [-h] filename config_file
        argparser_example.py: error: the following arguments are required: c
        

        这意味着我们的工具有问题

        第二轮:优化

        因此,为了使其成为可选,我将程序修改如下

            parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)
        

        帮助结果应该是

        usage: argparser_example.py [-h] [-c CONFIG] filename
        
        This example for a tool to process a file and configure the tool using a config file.
        
        positional arguments:
          filename              Input file either text, image or video
        
        optional arguments:
          -h, --help            show this help message and exit
          -c CONFIG, --config CONFIG
                                a JSON file to load the initial configuration
        

        所以当我执行程序时

        (base) > python .\argparser_example.py filename.txt
        

        结果是

        The file to be processed is filename.txt
        The config file is configFile.json
        and all arguments are:  Namespace(config_file='configFile.json', filename='filename.txt')
        

        带有类似的参数

        (base) > python .\argparser_example.py filename.txt --config_file anotherConfig.json
        

        结果是

        The file to be processed is filename.txt
        The config file is anotherConfig.json
        and all arguments are:  Namespace(config_file='anotherConfig.json', filename='filename.txt')
        

        第 3 轮:增强功能

        要将标志名称从--config_file 更改为--config,同时保持变量名称不变,我们修改代码以包含dest='config_file',如下所示:

        parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', dest='config_file')
        

        命令将是

        (base) > python .\argparser_example.py filename.txt --config anotherConfig.json
        

        要添加对具有调试模式标志的支持,我们需要在参数中添加一个标志以支持布尔调试标志。为了实现它,我添加了以下内容:

            parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )
        

        工具命令将是:

        (carnd-term1-38) > python .\argparser_example.py image.jpg -c imageConfig,json --debug
        

        结果是

        The file to be processed is image.jpg
        The config file is imageConfig,json
        Debug mode enabled
        and all arguments are:  Namespace(config_file='imageConfig,json', debug=True, filename='image.jpg')
        

        【讨论】:

          【解决方案12】:

          使用 argparse 并修改“-h”/“--help”开关以显示您自己的个人代码帮助说明的一个非常简单的方法是将默认帮助设置为 False,您还可以添加尽可能多的附加 .add_arguments随你喜欢:

          import argparse
          
          parser = argparse.ArgumentParser(add_help=False)
          
          parser.add_argument('-h', '--help', action='help',
                          help='To run this script please provide two arguments')
          parser.parse_args()
          

          运行:python test.py -h

          输出:

          usage: test.py [-h]
          
          optional arguments:
            -h, --help  To run this script please provide two arguments
          

          【讨论】:

            【解决方案13】:

            对此很陌生,但将 Python 与 Powershell 相结合并使用此模板,灵感来自于一个深入而伟大的 Python Command Line Arguments – Real Python

            您可以在init_argparse() 中做很多事情,我在这里只介绍最简单的场景。

            1. import argparse
            2. 使用if __name__ == "__main__": main() 模式从终端执行
            3. 解析 main() 函数中的参数,该函数没有参数
            4. 定义一个init_argparse()函数
              • 通过调用argparse.ArgumentParser()创建解析器对象
              • parser.add_argument("--<long_param_name>")声明一个或多个参数
              • 返回解析器
            5. 通过调用parser.parse_args() 创建args 对象来解析args
            6. param1, param2, ... 定义一个适当的函数
            7. 调用function_proper,参数被分配为args对象的属性
              • 例如`function_proper(param1=args.param1, param2=args.param2)
            8. 在 shell 中使用命名参数调用模块:
              • 例如python foobar.py --param1="foo" --param2=="bar"
            #file: foobar.py
            import argparse
            
            def function_proper(param1, param2):
                #CODE...
            
            def init_argparse() -> argparse.ArgumentParser:
                parser = argparse.ArgumentParser()
                parser.add_argument("--param1")
                parser.add_argument("--param2")
                return parser
            
            
            def main() -> None:
                parser = init_argparse()
                args = parser.parse_args()
                function_proper(param1=args.param1, param2=args.param2)
            
            
            if __name__ == "__main__":
                main()
            
            >>> python .\foobar.py --param1="foo" --param2=="bar"
            

            【讨论】:

              【解决方案14】:

              由于您尚未阐明参数“A”和“B”是位置参数还是可选参数,所以我将两者混合。

              默认情况下需要位置参数。如果不给出,则会抛出“给出的参数很少”,而以它们的名字命名的可选参数则不是这种情况。默认情况下,该程序将接受一个数字并返回其平方,如果使用立方体选项,它将返回其立方体。

              import argparse
              parser = argparse.ArgumentParser('number-game')
              parser.add_argument(
                  "number",
                  type=int,
                  help="enter a number"
                 )
              parser.add_argument(
                 "-c", "--choice",
                 choices=['square','cube'],
                 help="choose what you need to do with the number"
              )
              
              # all the results will be parsed by the parser and stored in args
              args = parser.parse_args()
              
              # if square is selected return the square, same for cube 
              if args.c == 'square':
                  print("{} is the result".format(args.number**2))
              elif args.c == 'cube':
                  print("{} is the result".format(args.number**3))
              else:
                  print("{} is not changed".format(args.number))
              

              用法

              $python3 script.py 4 -c square
              16
              

              这里的可选参数是有价值的,如果你只是想把它当作一个标志来使用,你也可以。因此,通过将 -s 用于正方形和 -c 用于立方体,我们可以通过添加 action = "store_true" 来改变行为。仅在使用时才变为true。

              parser.add_argument(
                  "-s", "--square",
                  help="returns the square of number",
                  action="store_true"
                  )
              parser.add_argument(
                  "-c", "--cube",
                  help="returns the cube of number",
                  action="store_true"
                  )
              

              所以条件块可以改成,

              if args.s:
                  print("{} is the result".format(args.number**2))
              elif args.c:
                  print("{} is the result".format(args.number**3))
              else:
                  print("{} is not changed".format(args.number))
              

              用法

              $python3 script.py 4 -c
              64
              

              【讨论】:

                【解决方案15】:

                作为现有答案的补充,如果你足够懒惰,可以使用名为protoargs 的代码生成工具。它从配置中生成参数解析器。对于 python,它使用 argparse

                带有可选 A 和 B 的配置

                syntax = "proto2";
                message protoargs
                {
                    optional string A     = 1; // A param description
                    optional string B     = 2; // B param description
                }//protoargs
                

                需要 A 和 B 的配置

                syntax = "proto2";
                message protoargs
                {
                    required string A     = 1; // A param description
                    required string B     = 2; // B param description
                }//protoargs
                

                位置 A 和 B 的配置

                syntax = "proto2";
                message protoargs
                {
                    required string A     = 1; // A param description
                    required string B     = 2; // B param description
                }//protoargs
                message protoargs_links
                {
                }//protoargs_links
                

                现在你应该运行的是:

                python ./protoargs.py -i test.proto -o . --py
                

                并使用它(这里可以举其他例子):

                import sys
                import test_pa
                
                class ArgsParser:
                    program = "test"
                    description = "Simple A and B parser test."
                
                    def parse(self, argv):
                        self.config = test_pa.parse(self.program, self.description, argv)
                
                    def usage(self):
                        return test_pa.usage(self.program, self.description)
                
                if __name__ == "__main__":
                    parser = ArgsParser()
                
                    if len(sys.argv) == 1:
                        print(parser.usage())
                    else:
                        parser.parse(sys.argv[1:])
                
                        if parser.config.A:
                            print(parser.config.A)
                
                        if parser.config.B:
                            print(parser.config.B)
                

                如果您想要更多 - 更改配置、重新生成解析器、使用更新的 parser.config。

                UPD:如规则中所述,我必须指定这是我自己的项目

                【讨论】:

                  【解决方案16】:

                  最简单的答案!

                  附:编写argparse文档的人很愚蠢

                  python 代码:

                  import argparse
                  parser = argparse.ArgumentParser(description='')
                  parser.add_argument('--o_dct_fname',type=str)
                  parser.add_argument('--tp',type=str)
                  parser.add_argument('--new_res_set',type=int)
                  args = parser.parse_args()
                  o_dct_fname = args.o_dct_fname
                  tp = args.tp
                  new_res_set = args.new_res_set
                  

                  运行代码

                  python produce_result.py --o_dct_fname o_dct --tp father_child --new_res_set 1
                  

                  【讨论】:

                  • 这个答案没有添加任何新的/与现有答案不同的东西。
                  猜你喜欢
                  • 1970-01-01
                  • 2020-03-22
                  • 2021-11-11
                  • 2011-09-03
                  • 2023-03-25
                  • 2018-07-17
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多