有這樣一個py文件,須要傳一個字典做爲參數:python
import json import sys def parse_params(data): json_data = json.loads(data[1]) print json_data if __name__=='__main__': params = sys.argv print params parse_params(params)
命名爲sp.py,運行的時候傳入以下參數:shell
#python sp.py '{"mode":"1","cdCmd":"cd src/test"}' ['sp.py', '{"mode":"1","cdCmd":"cd src/test"}'] {u'cdCmd': u'cd src/test', u'mode': u'1'}
ok,沒問題。可是想寫shell腳本經過變量的方式傳入參數,這時遇到了問題。json
shell腳本以下:python2.7
mode="1" cdCmd="cd src/test" python sp.py '{"mode":"'$mode'","cdCmd":"'$cdCmd'"}'
運行結果以下:spa
#./test.sh ['sp.py', '{"mode":"1","cdCmd":"cd', 'src/test"}'] Traceback (most recent call last): File "sp.py", line 10, in <module> parse_params(params) File "sp.py", line 4, in parse_params json_data = json.loads(data[1]) File "/usr/local/python27/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/usr/local/python27/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/python27/lib/python2.7/json/decoder.py", line 382, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Unterminated string starting at: line 1 column 21 (char 20)
發現很奇怪,cdCmd變量被分割成了兩個參數:"cdCmd":"cd', 'src/test"。code
上網查閱資料後發現是由於shell會把空格做爲分隔符,因此成了兩個變量。這個問題目前找到兩個解決辦法:blog
1.能夠經過修改環境變量IFS來實現,默認IFS是空,改爲別的字符便可。string
2.加引號也但是實現帶空格參數的傳遞,修改shell腳本以下:it
mode="1" cdCmd="cd src/test" python sp.py '{"mode":"'$mode'","cdCmd":"'"$cdCmd"'"}'
運行結果:ast
# ./test.sh ['sp.py', '{"mode":"1","cdCmd":"cd src/test"}'] {u'cdCmd': u'cd src/test', u'mode': u'1'}