1

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?

Community
  • 1
  • 1
Spot
  • 83
  • 1
  • 7
  • 2
    You are looking for something like "import *" - NOT a recommended practice. See answers in http://stackoverflow.com/questions/2360724/in-python-what-exactly-does-import-import . – gimel Apr 24 '12 at 04:50
  • Solution: don't. You shouldn't be doing `from ... import *` imports in general anyway as it makes tracing through the code much harder. – Chris Morgan Apr 24 '12 at 04:51
  • I want the user to supply a list of parameters for the simulation, and for whatever parameters that he doesnt supply, the defaults will be used. So I was thinking of running my code which assigns all the default values for the parameters, and then doing an execfile('parm.py') which will override all the variables the user has supplied. Is there a more elegant way to do this? – Spot Apr 24 '12 at 05:09

2 Answers2

7

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
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
1

You can use execfile() for this, but you should consider another way altogether.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Is there any simple way of doing this? For a while I was thinking of passing them as arguments on the command line, but there are just too many of them. – Spot Apr 24 '12 at 04:52