【问题标题】:Multiple command line arguments多个命令行参数
【发布时间】:2015-11-30 22:46:34
【问题描述】:

我一直在研究一点 Python,并且遇到了用于解析命令行参数的 getopt 模块。

基本上,我有以下代码:

import sys, getopt

print("The list of %s arguments passed:" % len(sys.argv))

# Print each argument
for arg in sys.argv:
    print(arg)
print()

# Now print parsed arguments
opts, args = getopt.getopt(sys.argv[1:], "ab:cd", ["arbitrary", "balance=", "cite"])
for opt in opts:
    print(opt)
print()

# Print the arguments returned
print(args)

但是,我需要 -b 选项来接受两个不同的参数,例如 -b one two。我试过在getopt的参数列表中的b后面加两个冒号,但是没有用。

如果有人能告诉我如何使用getopt 模块并发布示例,那将非常有用!

【问题讨论】:

  • 请注意 getopt 已弃用;改用更通用的argparse module。它支持每个选项的多个值。
  • 相关阅读 - PEP 0389 其中提到了deprecation of optparsede-emphasized getopt
  • 使用argparse并用双引号将参数括起来-b "argument with spaces"
  • @MartijnPieters 啊啊啊,我不知道!有时我忘记了我正在阅读几年前写的“潜入 Python”......也许如果你把你的评论变成一个答案,我会接受它作为主要答案:)
  • @MatGomes 为什么不将-b 分成两个参数?

标签: python command-line command-line-arguments


【解决方案1】:

忘记getopt,使用Docopt(真的):

如果我理解得很好,您希望用户传递 2 个参数来平衡。这可以通过以下方式实现:

doc = """Usage:
   test.py balance= <b1> <b2>
   test.py
"""

from docopt import docopt

options, arguments = docopt(__doc__)  # parse arguments based on docstring above

此程序接受:test.py balance= X Y,或不接受任何参数。

现在,如果我们添加 'cite' 和 'arbitrary' 选项,这应该会给我们:

doc = """
Usage:
   test.py balance= <b1> <b2>
   test.py

Options:
   --cite -c           Cite option 
   --arbitrary -a      Arbitrary option   
"""

程序现在接受选项。 示例:

test.py balance= 3 4 --cite

=> options = {
    "--arbitrary": false, 
    "--cite": true, 
    "<b1>": "3", 
    "<b2>": "4", 
    "balance=": true
}

提示:另外,您可以在代码中使用之前test your documentation string directly in your browser

救命!

【讨论】:

  • 我目前正在研究 argparse 模块,一旦我了解了 argparse ,我将看看 docopt 模块。哪个应该更好/更简单? argparse 还是 docopt?
  • 我学习了 argparse,然后是 Docopt。我意识到我学了 argparse 是白费的,因为 Docopt 很简单,你不必学习 API,你只需要学习(如果你还不知道的话)一个标准。这也用于 Linux 手册页,因此您应该习惯它。
  • 如果你正在寻找真正(真的)更复杂的东西,你可以看看Click
猜你喜欢
  • 2012-11-05
  • 2014-06-05
  • 1970-01-01
  • 1970-01-01
  • 2018-09-28
  • 1970-01-01
  • 2012-01-28
  • 2015-03-16
  • 2014-12-08
相关资源
最近更新 更多