簡體   English   中英

多個命令行參數

[英]Multiple 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= XY或不包含任何參數。

現在,如果我們添加“引用”和“任意”選項,這應該給我們:

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
}

提示 :另外,您可以在代碼中使用文檔字符串之前直接在瀏覽器中測試文檔字符串

救生員!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM