Here's a snippet using import for reading Python-based configuration files that are specified at runtime.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# To run this code, create a python file, say config.py, with a sample parameter # called sample_param. import os import sys def main(): if len(sys.argv) == 1: print "usage: %s config_file" % os.path.basename(sys.argv) sys.exit(2) config_file = os.path.basename(sys.argv) if config_file[-3:] == ".py": config_file = config_file[:-3] data_config = __import__(config_file, globals(), locals(), ) print data_config.sample_param main()
Reading configuration files is a common activity in scientific programming. Engineers typically create extensive config file reading libraries for handling this task.
Often there are a number of alternative configuration files that are appropriate for a single application. In order to avoid changing the import declaration, the above paradigm can be used at runtime.
Using Python scripts to store configuration information is a powerful and simple technique that can support documentation through comments, parameter checking as well as the creation of derived variables. In systems where other programming languages are required, the config file information stored in Python files can be converted to custom configuration files for system applications.
Also see the recipe: Importing from a Module Whose Name Is Determined at Runtime by Jurgen Hermann.