Getting Variables from a file
Andrew Dalke
dalke at acm.org
Sat May 27 23:15:30 EDT 2000
emile at fenx.com wrote:
>for line in vars.split("\n"):
> try:
> k,v = line.split(" = ")
> exec (line)
> except:
> # doexn't parse out as tuple w/ interspersed =
> pass
>
>print dof,elements,mesh_dof
>
>is safer. I'm sure there's still a hole in that, I just
>don't see it right now.
Consider a line of the form:
a = __import__('os').system('nasty command, like: remove the file system')
Don't think you would like the results.
Back to the original poster ...
Since the file contains lines which are also Python code, if you trust
the file contents, then the easiest command is
execfile("filename")
You don't say why you want this ability. The most obvious thing is
to read in some configuration parameters for code which expects those
variable names.
If you expect to make it available in a possibly hostile environment
(like the web) then you'll need better protection so make sure the
lines are of the right format. For example:
vars = open("filename".read()
import re
line_format = re.compile(r"^\s*\w+\s*=\s*\d+\s*$")
for line in vars.split("\n"):
if line_format.match(line):
exec line
else:
raise "Line not in the proper format: " + line
A better overall solution would be to have the function take keyword
parameters, like:
def do_something(dof = 6, elements = 1, mesh_dof = 300):
# Your code here
pass
then read in the values into a dictionary then use 'apply', like:
infile = open("filename")
variables = {}
while 1:
line = infile.readline()
if not line:
break
name, val = string.split(line)
variables[name] = int(val)
apply(do_something, [], variables)
You could also do
variables = {}
# don't allow access to any functions
exec open("filename").read() in {'__builtins__': {}}, variables
for k,v in variables.items():
variables[k] = int(v) # make sure the values are integers
apply(do_something, [], variables)
which is just as safe, but more complicated.
Oh, and I haven't tested any of this.
Andrew
dalke at acm.org
More information about the Python-list
mailing list