ConfigParserというモジュール使うと簡単です。
import ConfigParser
CONFIGFILE = 'setting.ini'
config = ConfigParser.ConfigParser()
if os.path.exists(CONFIGFILE):
config.read(CONFIGFILE)
if config.has_section('DB'):
if config.has_option('DB', "address"):
HOST = config.get('DB', "address")
if config.has_option('DB', "port"):
PORT = config.getint('DB', "port")
if self.config.has_option('DB', "user"):
USER = config.get('DB', "user")
if self.config.has_option('DB', "password"):
PASSWD = self.config.get('DB', "password")
setting.ini
[DB]
DB_address = 192.168.0.123
DB_port = 3306
DB_user = hajime
DB_password = hogehoge
DB_dbName = db1
で、問題は複雑なファイル構成になってきた場合の設定ファイルの置き場所なんですよね。
ありそうな問題
- py2exe使うのでスクリプトとexeになるとき別のパスに動く可能性あり。
- 細かいスクリプト群はまとめて別のフォルダにあり、そちらからも設定ファイルを見たい。ちなみにこれらのスクリプトはpy2exeによりlibrary.zip内に置かれる・・・つまり相対パスが変わる。
C:/Documents and Settings/User内に放り込むという手も使える。
exeと同じ場所と両方にiniファイルが合った場合、ドキュメント内の方が使われるっぽい(適当検証ですが)
もっと適当に使いたい
表示設定とか、あまり大事じゃないけど
頻繁に適当に変更したり保存したりしたい場合用に作りました。
import os.path
import ConfigParser
CONFIGFILE = 'options.ini'
def saveOption(name, val):
config = ConfigParser.ConfigParser()
if os.path.exists(CONFIGFILE):
config.read(CONFIGFILE)
if not config.has_section('OPTIONS'):
config.add_section('OPTIONS')
config.set('OPTIONS', name, val)
# save to file
o=open(CONFIGFILE,'w')
config.write(o)
o.close()
def getOption(name):
if not os.path.exists(CONFIGFILE):
return None
config = ConfigParser.ConfigParser()
config.read(CONFIGFILE)
if not config.has_section('OPTIONS'):
return None
if config.has_option('OPTIONS', name):
return config.get('OPTIONS', name)
else:
return None
saveOption('value1', '123')
で保存して
getOption('value1')
で値を取ることができて楽です。
wx
ファイルの置き場所が問題となってくるのですが、こんな便利関数が。
wx.StandardPaths.GetConfigDir()
でReturn the directory with system config files:
/etc under Unix,
'c:/Documents and Settings/All Users/Application Data' under Windows, /Library/Preferences for Mac
だそうです。
wxPython.org
めもっぽ
最終更新:2009年07月08日 13:55