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?

3
  • 2
    You are looking for something like "import *" - NOT a recommended practice. See answers in stackoverflow.com/questions/2360724/… . Commented Apr 24, 2012 at 4:50
  • Solution: don't. You shouldn't be doing from ... import * imports in general anyway as it makes tracing through the code much harder. Commented Apr 24, 2012 at 4: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? Commented Apr 24, 2012 at 5:09

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.