ich möchte meine Konfigurationsdateien zukünftig auslagern, bisher speichere ich die Werte noch all zu oft direkt in den Skripten. Ich habe mit ein Skript geschrieben, welches prüft, ob ob eine Konfigurationsdatei existiert und diese gegebenenfalls anlegt. Dann werden die Werte geprüft und auch diese ggf. angelegt.
Ich bin soweit zufrieden, glaube aber dass da noch erheblich was zu optimieren ist um den Code auch kleiner zu machen. Ich freue mich über Vorschläge. Danke
Code: Alles auswählen
#!/usr/bin/python
# -*- coding: utf8 -*-
import os
from ConfigParser import SafeConfigParser
CONFIGFILE = os.path.join ( os.path.expanduser("~"), ".config/myconfigfile.ini" )
parser = SafeConfigParser()
CONFIGFILE_SECTION = "data"
CONFIGFILE_OPTIONS = [ "username", "password", "signatur", "environment" ]
def write_configfile( section, options ):
with open( CONFIGFILE , "w" ) as configfile:
print "writing config file ..."
parser.add_section( section )
for option in options:
temp_input = raw_input( "please enter {0}: ".format( option) )
parser.set( section, option, "{0}".format( temp_input ) )
parser.write(configfile)
def updating_configfile( section, options ):
with open( CONFIGFILE , "w+" ) as configfile:
print "updating config file ..."
if not section in parser.sections():
parser.add_section( section )
for option in options:
temp_input = raw_input( "please enter {0}: ".format( option) )
parser.set( section, option, "{0}".format( temp_input ) )
parser.write(configfile)
def read_configfile( section, options ):
print "reading config file", CONFIGFILE
parser.read( CONFIGFILE )
while not section in parser.sections():
print "config file corrupt, writing new one ..."
write_configfile( CONFIGFILE_SECTION, CONFIGFILE_OPTIONS )
for option in [ "username", "password", "signatur", "environment" ]:
if not parser.has_option( "data", option ):
print "option {0} is missing".format( option )
if parser.get( "data", option ) == "":
print "option {0} has no value".format( option )
updating_configfile( CONFIGFILE_SECTION, [ option ] )
read_configfile( CONFIGFILE_SECTION, CONFIGFILE_OPTIONS )
## check configfile exists
if os.path.exists( CONFIGFILE ):
print "configfile exists"
read_configfile( CONFIGFILE_SECTION, CONFIGFILE_OPTIONS )
else:
print "configfile not exists"
write_configfile( CONFIGFILE_SECTION, CONFIGFILE_OPTIONS )
read_configfile( CONFIGFILE_SECTION, CONFIGFILE_OPTIONS )
username = parser.get( "data", "username")
password = parser.get( "data", "password")
signatur = parser.get( "data", "signatur")
environment = parser.get( "data", "environment")