【问题标题】:How to use getopt/OPTARG in Python? How to shift arguments if too many arguments (9) are given?如何在 Python 中使用 getopt/OPTARG?如果给出太多参数(9),如何转换参数?
【发布时间】:2011-06-17 07:44:04
【问题描述】:

如何在 Python 中使用 getopt/optarg?

【问题讨论】:

    标签: python arguments command-line-interface getopt


    【解决方案1】:

    这是我如何做的一个例子,我通常使用相同的基本模板:

    import sys
    import getopt
    
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'm:p:h', ['miner=', 'params=', 'help'])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
            sys.exit(2)
        elif opt in ('-m', '--miner'):
            miner_name = arg
        elif opt in ('-p', '--params'):
            params = arg
        else:
            usage()
            sys.exit(2)
    

    我认为没有任何 9 个参数的限制。

    【讨论】:

    • “argv”需要是“sys.argv”
    • 您需要从 argv 数组中删除脚本名称,例如:arvg[1:] 以使该行生效:opts, args = getopt.getopt(argv[1:], 'm:p:h', ['miner=', 'params=', 'help'])
    • 使用什么usage()函数?
    【解决方案2】:

    谷歌搜索会有所帮助。看看标准库中的getoptargparse 模块:

    import argparse
    
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                       help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                       const=sum, default=max,
                       help='sum the integers (default: find the max)')
    
    args = parser.parse_args()
    print args.accumulate(args.integers)
    

    然后按预期运行:

    $ prog.py -h
    usage: prog.py [-h] [--sum] N [N ...]
    
    Process some integers.
    
    positional arguments:
     N           an integer for the accumulator
    
    optional arguments:
     -h, --help  show this help message and exit
     --sum       sum the integers (default: find the max)
    

    当使用适当的参数运行时,它会打印命令行整数的总和或最大值:

    $ prog.py 1 2 3 4
    4
    
    $ prog.py 1 2 3 4 --sum
    10
    

    这直接来自标准库。

    【讨论】:

    • Argparse 及其教程很棒。
    • 抱歉添加,但我建议您先查看docopt,然后再深入了解argparse...
    【解决方案3】:

    您是否尝试过阅读模块getopt (http://docs.python.org/library/getopt.html?highlight=getopt#module-getopt) 的python 文档?它提供了一个如何使用getopt 的简单示例。转移参数是什么意思?如果要检查用户使用的参数是否不超过 9 个,可以检查 sys.argv 列表的长度,其中包含传递给脚本的所有选项/参数。第一个元素是调用的脚本的名称,因此长度始终至少为 1。您可以执行以下操作:

    if len(sys.argv) > 10
        print('Too many arguments.')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多