0
我正在嘗試編寫一個實用程序,讓我可以根據配置文件將命令設置爲在unix shell中運行。從本質上講,我希望能夠給一個[Command List]
和預期[Response List]
。這裏是我的配置文件中的一個例子:使用ConfigParser讀取字符串作爲配置值
# Command File
# List of commands to be carried out for each host listed in `veri.serv.cfg`
[Command List]
; T server
nc -zw1 159.1.1.1 9988 | gawk '{print $7}'
; P Server
nc -zw1 sup.serv.com 8050 | gawk '{print $7}'
; G L Service
nc -zw1 hi.serv.com 80 | gawk '{print $7}'
; L and N Hosts
nc -zw1 l.serv.com 80 | gawk '{print $7}'
nc -zw1 ln.serv.com 443 | gawk '{print $7}'
nc -zw1 llnn.serv.com 443 | gawk '{print $7}'
然而,當我試圖解析使用parser.items('Command List')
它,我得到:
File "veri.py", line 22, in <module>
print subConfigParser.read(os.path.join(relativeRunPath, 'veri.cfg'))
File "/usr/lib/python2.7/ConfigParser.py", line 305, in read
self._read(fp, filename)
File "/usr/lib/python2.7/ConfigParser.py", line 546, in _read
raise e
ConfigParser.ParsingError: File contains parsing errors
[line 6]: "nc -zw1 159.1.1.1 9988 | gawk '{print $7}'\n"
[line 9]: "nc -zw1 sup.serv.com 8050 | gawk '{print $7}'\n"
[line 12]: "nc -zw1 hi.serv.com 80 | gawk '{print $7}'\n"
[line 15]: "nc -zw1 l.serv.com 80 | gawk '{print $7}'\n"
[line 16]: "nc -zw1 ln.serv.com 443 | gawk '{print $7}'\n"
[line 17]: "nc -zw1 llnn.serv.com 443 | gawk '{print $7}'\n"
使用SafeConfigParser
作爲值時,我不能以完整的字符串讀取嗎?
完整文件:
#! /usr/bin/python25
import os
import ConfigParser
# --- sudo consts --- #
# relative path, regardless of where we're executing from
RELATIVE_PATH = os.path.abspath(os.path.dirname(__file__))
BASE_SERVER_FILE = os.path.join(RELATIVE_PATH, 'cfg', 'veri.serv.cfg')
BASE_CONFIG_FILE = os.path.join(RELATIVE_PATH, 'cfg', 'veri.base.cfg')
# --- end consts --- #
baseConfigParser = ConfigParser.SafeConfigParser()
baseConfigParser.read(BASE_CONFIG_FILE)
runlist = baseConfigParser.get('Config List', 'runlist').strip().split("\n")
print runlist
for subDir in runlist:
print subDir
relativeRunPath = os.path.join(RELATIVE_PATH, subDir)
subConfigParser = ConfigParser.SafeConfigParser()
subConfigParser.read(os.path.join(relativeRunPath, 'veri.cfg'))
print subConfigParser.items('Command List') ###### <<< Error Here
if os.path.isfile(os.path.join(relativeRunPath, 'veri.serv.cfg')):
subServSpecified = true
subServConfigParser = ConfigParser.SafeConfigParser()
subServConfigParser.read(os.path.join(relativeRunPath, 'veri.serv.cfg'))
print subServConfigParser.get('Config List', 'runlist')
嗯,這是不幸的 - 所以沒有辦法沒有一個選項,值對? – MrDuk 2014-10-07 18:38:57
如果你喜歡你的格式到一個標準的ini文件,你可以編寫你自己的解析器。您會過濾掉以「;」開頭的行或者是空白的,請掃描「[xx]」並將其餘行添加到您自己的字典中。 – tdelaney 2014-10-07 18:46:59