0

/etc/sysconfig/ に構成ファイル FOO があります。この Linux ファイルは INI ファイルに非常に似ていますが、セクション宣言がありません。

このファイルから値を取得するために、私は次のようなシェル スクリプトを作成していました。

source /etc/sysconfig/FOO
echo $MY_VALUE

今、私はpythonで同じことをしたいと思っています。ConfigParser を使用しようとしましたが、ConfigParser は、セクション宣言がない限り、このような INI ファイルのような形式を受け入れません。

そのようなファイルから値を取得する方法はありますか?

4

2 に答える 2

1

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.

于 2010-05-20T08:11:10.897 に答える
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 はその filelike オブジェクトを読み取ります。

于 2010-05-20T08:20:47.733 に答える