2014-04-29 30 views
0

我想創建Python腳本讀取參數到一個字典,然後打印如何閱讀Python腳本的參數到字典

腳本調用與

python lookup.py "[email protected], sender-ip=10.10.10.10" 
「發送器IP」的價值

這裏是腳本

from sys import argv 

script, input = argv 

attributeMap = {} 
delimiter = "=" 
for item in input: 

    if delimiter in item: 
     tuple = item.split(delimiter) 
     print tuple[0] 
     print tuple[1] 
     attributeMap[tuple[0]]= tuple[1] 
     print attributeMap[tuple[0]] 

print attributeMap['sender-ip'] 
+0

你的'sender-ip'項目使用'-'而不是'=';一個錯字?無論如何我已經糾正它。 –

+0

不要影響內置的'輸入'功能。 – IceArdor

+0

'argparse'模塊用於解析命令行參數。 https://docs.python.org/dev/library/argparse.html – IceArdor

回答

2

input是不是列表;它是一個字符串。你需要該字符串首先分成項目:

items = input.split(', ') 
for item in items: 

請注意,有一個名爲input()以及一個內置的功能,儘量不使用名稱和掩蓋了內置。

下面是一些代碼,從你的輸入產生字典:

import sys 

argument = sys.argv[1] 
attr_map = dict(item.strip().split('=', 1) for item in argument.split(',')) 
print attr_map['sender-ip'] 
+0

@martjin pieters ---試過了,仍然不起作用 – Glowie

+0

定義「不起作用」。你有例外嗎?如果是這樣,追溯是什麼? –

+0

讓我讀你發佈的新東西,然後我可以更好地解釋 – Glowie

1

顯然你的意思"[email protected], sender-ip=10.10.10.10"

這裏有一個片段:

def toDict(s): 
    result = {} 
    for piece in s.split(','): 
    # piece is like 'foo=bar' here 
    key, value = piece.split('=') 
    result[key.strip()] = value.strip() # .strip() removes spaces around 
    return result 

它是如何工作的:

>>> arg_string = "[email protected], sender-ip=10.10.10.10" 
>>> toDict(arg_string) 
{'email': '[email protected]', 'sender-ip': '10.10.10.10'} 
>>> _ 
2

隨着docopt這很容易。

已經安裝docopt

$ pip install docopt 

重寫你的解決方案,這樣lookup.py

"""Usage: lookup.py <e-mail> <sender-ip> 

Arguments: 
    <e-mail>  e-mail address 
    <sender-ip> IP address 

Sample use: 

    $ python lookup.py [email protected] 1.2.3.4 
""" 
from docopt import docopt 

if __name__ == "__main__": 
    args = docopt(__doc__) 
    attributeMap = {"e-mail": args["<e-mail>"], "sender-ip": args["<sender-ip>"]} 
    print attributeMap 

和命令行調用。

首先要記住,如何調用它(我選擇的位置參數,你可以使用選項太)

$ python lookup.py -h 
Usage: lookup.py <e-mail> <sender-ip> 

Arguments: 
    <e-mail>  e-mail address 
    <sender-ip> IP address 

Sample use: 

    $ python lookup.py [email protected] 1.2.3.4 

終於看到,你怎麼要求被填充的詞典:

$ python lookup.py [email protected] 1.2.34 
{'e-mail': '[email protected]', 'sender-ip': '1.2.34'} 
+0

當然,除非OP實際上試圖從其他來源解析字符串格式。 –