使用configpar将字符串作为配置值读取

2024-09-28 17:02:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个实用程序,它可以让我根据配置文件设置在unixshell中运行的命令。本质上,我希望能够给出一个[Command List]和一个预期的[Response List]。。下面是我的一个配置文件的示例:

# 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')解析它时,我得到:

^{pr2}$

我不能用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')

Tags: pathcomoscfgcommandlistprintjoin
1条回答
网友
1楼 · 发布于 2024-09-28 17:02:48

配置文件对ConfigParser使用的格式无效。例如,需要用一系列选项来命名它

[T server]
commands = nc -zw1 159.1.1.1 9988 | gawk '{print $7}'

[P Server]
commands = nc -zw1 sup.serv.com 8050 | gawk '{print $7}'

[G L Service]
commands = nc -zw1 hi.serv.com 80 | gawk '{print $7}'

[L and N Hosts]
commands = 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}'

然后可以得到值

^{pr2}$

相关问题 更多 >