2015-09-04 177 views
1

我一直在研究一些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選項採取兩種不同說法,E.g -b one two。我嘗試在getopt的參數列表中放置兩個冒號b,但它不起作用。

如果有人可以告訴我如何使用getopt模塊和後置示例來實現此功能,那將非常有用!

+2

請注意'getopt'已被棄用;改爲使用更通用的['argparse'模塊](https://docs.python.org/2/library/argparse.html)。它支持每個選項的多個值。 –

+1

相關閱讀 - [PEP 0389](https://www.python.org/dev/peps/pep-0389/)其中提及[棄用'optparse'](https://www.python.org/dev/peps/pep-0389 /#deprecation-of-optparse)和[de-emphasis'getopt'](https://www.python.org/dev/peps/pep-0389/#updates-to-getopt-documentation ) –

+0

使用'argparse'並用雙引號'-b「參數括住空格」' –

回答

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,或沒有參數這可以通過以下來達到的。

現在,如果我們加上「引用」和「任意」選項,這應該給我們:

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在代碼中使用它。

拯救生命!

+2

請發佈解決* actual *問題的代碼。 –

+0

好點@KolyolyHorvath,我會編輯我的帖子 – brunetton

+0

我目前正在研究argparse模塊,一旦理解了argparse,我會看看docopt模塊。哪一個應該更好/更簡單? argparse還是docopt? –