如何在 Python 中从 etc/sysconfig 检索值

发布于 2024-09-02 13:54:30 字数 298 浏览 3 评论 0原文

我在 /etc/sysconfig/ 中有一个配置文件 FOO。这个 Linux 文件与 INI 文件非常相似,但没有段声明。

为了从此文件中检索值,我曾经编写一个 shell 脚本,如下所示:

source /etc/sysconfig/FOO
echo $MY_VALUE

现在我想在 python 中做同样的事情。我尝试使用ConfigParser,但是ConfigParser不接受这样的INI-File类似格式,除非它有一个节声明。

有什么方法可以从这样的文件中检索值吗?

I have a config file FOO in /etc/sysconfig/. This Linux file is very similar to INI-File, but without a section declaration.

In order to retrieve a value from this file, I used to write a shell script like:

source /etc/sysconfig/FOO
echo $MY_VALUE

Now I want to do the same thing in python. I tried to use ConfigParser, but ConfigParser does not accept such an INI-File similar format, unless it has a section declaration.

Is there any way to retrieve value from such a file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

记忆で 2024-09-09 13:54:30

我想您可以使用 subprocess 模块并读取其输出来完全执行您对 shell 脚本所做的操作。将它与设置为 Trueshell 选项一起使用。

I suppose you could do exactly what you're doing with your shell script using the subprocess module and reading it's output. Use it with the shell option set to True.

流云如水 2024-09-09 13:54:30

如果您想使用 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 读取该文件类对象。

If you want to use ConfigParser, you could do something like:

#! /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")

The code creates an in-memory filelike object containing a [main] section header and the contents of the specified file. ConfigParser then reads that filelike object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文