Welcome, guest | Sign In | My Account | Store | Cart

Here's a snippet using import for reading Python-based configuration files that are specified at runtime.

Python, 20 lines
 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[0])
        sys.exit(2)

    config_file = os.path.basename(sys.argv[1])
    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.

1 comment

Leonardo Santagada 18 years, 1 month ago  # | flag

A litle problem. if you are taking the basepath as in: config_file = os.path.basename(sys.argv[1]) and then importing conif_file you will have problems if the config file resides in another dir. what you can do is:

config_path, config_file = os.path.split(sys.argv[1])
if config_path != '':
  sys.path.append(config_path)

but i don't really know if this is going to work, maybe it's better to just print an error message.