Search code examples
pythonimportpython-module

Including external files in Python


I am writing a Python script which runs some simulations, but it takes in a lot of input parameters (about 20). So I was thinking of including all the simulation parameters in an external file. What's the easiest way of doing this?

One answer I found was in Stack Overflow question How to import a module given the full path?, putting all the simulation parameters in a file parm.py and importing that module using the imp package.

This would allow the user who runs this script to supply any file as input. If I import a module that way:

parm = imp.load_source('parm', '/path/to/parm.py')

then all the parameters have to be referenced as

parm.p1, parm.p2

However, I would just like to refer to them as p1, p2, etc. in my script. Is there a way to do that?


Solution

  • Importing arbitrary code from an external file is a bad idea.

    Please put your parameters in a configuration file and use Python's ConfigParser module to read it in.

    For example:

    ==> multipliers.ini <==
    [parameters]
    p1=3
    p2=4
    
    ==> multipliers.py <==
    #!/usr/bin/env python
    
    import ConfigParser
    
    config = ConfigParser.SafeConfigParser()
    config.read('multipliers.ini')
    
    
    p1 = config.getint('parameters', 'p1')
    p2 = config.getint('parameters', 'p2')
    
    print p1 * p2