python - 多个命令行参数

标签 python command-line command-line-arguments

我一直在学习一点 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,使用 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,或不接受任何参数。

现在,如果我们添加“引用”和“任意”选项,这应该给我们:

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在您的代码中使用它之前。

救星!

关于python - 多个命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32403762/

相关文章:

python - 在 Python 中使用 BeautifulSoup 从脚本标签中提取数据

perl - 如何从命令行检查我的系统上是否安装了 Perl 模块?

java - 将参数数组传递给 Quartz Scheduler

Python的argparse从几个可选参数中选择一个

git - merge Git 分支,同时保持各个分支布局

c++ - C++中客户端程序的可选命令行参数

python - 从文本文件中读取多个数字

python - 如何在 Django 中为 css 文件设置相对 url

python - 为什么使用 Python 生成器遍历二叉树比不使用慢得多?

java - 使用 DSC 安装 Windows 服务(所需状态配置)