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