如何在Python中从etc/sysconfig中获取值
我在 /etc/sysconfig/ 目录下有一个配置文件 FOO。这个 Linux 文件和 INI 文件很像,但没有章节声明。
为了从这个文件中获取一个值,我以前会写一个 shell 脚本,像这样:
source /etc/sysconfig/FOO
echo $MY_VALUE
现在我想用 Python 来做同样的事情。我尝试使用 ConfigParser,但 ConfigParser 不接受这种类似 INI 文件的格式,除非它有章节声明。
有没有什么办法可以从这样的文件中获取值呢?
2 个回答
1
如果你想使用 ConfigParser
,你可以这样做:
#! /usr/bin/env python2.6
from StringIO import StringIO
import ConfigParser
def read_configfile_without_sectiondeclaration(filename):
buffer = StringIO()
buffer.write("[main]\n")
buffer.write(open(filename).read())
buffer.seek(0)
config = ConfigParser.ConfigParser()
config.readfp(buffer)
return config
if __name__ == "__main__":
import sys
config = read_configfile_without_sectiondeclaration(sys.argv[1])
print config.items("main")
这段代码会创建一个在内存中的文件样对象,里面包含一个 [main] 的部分标题和指定文件的内容。然后,ConfigParser 就会读取这个文件样对象。
1
我想你可以用你现在的shell脚本做的事情,使用subprocess
模块来实现,并且读取它的输出。记得把shell
选项设置为True
。