This question is a follow-up to the question I asked here, which in summary was:
"In python how do I read in parameters from the text file params.txt
, creating the variables and assigning them the values that are in the file? The contents of the file are (please ignore the auto syntax highlighting, params.txt
is actually a plain text file):
Lx = 512 Ly = 512
g = 400
================ Dissipation =====================
nupower = 8 nu = 0
...[etc]
and I want my python script to read the file so that I have Lx, Ly, g, nupower, nu etc available as variables (not keys in a dictionary) with the appropriate values given in params.txt
. By the way I'm a python novice."
With help, I have come up with the following solution that uses exec():
with open('params.txt', 'r') as infile:
for line in infile:
splitline = line.strip().split(' ')
for i, word in enumerate(splitline):
if word == '=':
exec(splitline[i-1] + splitline[i] + splitline[i+1])
This works, e.g. print(Lx)
returns 512
as expected.
My questions are:
(1) Is this approach safe? Most questions mentioning the exec()
function have answers that contain dire warnings about its use, and imply that you shouldn't use it unless you really know what you're doing. As mentioned, I'm a novice so I really don't know what I'm doing, so I want to check that I won't be making problems for myself with this solution. The rest of the script does some basic analysis and plotting using the variables read in from this file, and data from other files.
(2) If I want to wrap up the code above in a function, e.g. read_params()
, is it just a matter of changing the last line to exec(splitline[i-1] + splitline[i] + splitline[i+1], globals())
? I understand that this causes exec()
to make the assignments in the global namespace. What I don't understand is whether this is safe, and if not why not. (See above about being a novice!)