Reputation: 2229
I have a text file in which there are several variables. Most of them are used in a Bash script of mine, but I'd like to use the same text file for my Python script. For the lines that are not properly formatted for Python, I want my script to just ignore. For those that are properly formatted, I want the script to check and if it's the variable I'm looking for - use it.
import sys import re
for ln in open("thefile.txt"):
m = re.match(r"(?P<varname>[^=]*)\s*=\s*(?P<value>.+)", ln)
if m:
varname = m.group("varname")
value_string = m.group("value")
value = eval(value_string)
print value
# so if the variables name is THISVARIABLE, get that value:
if varname == "THISVARIABLE":
mypythonvariable == value
I'm getting the following error:
NameError: name 'Somevariableinmytextfile' is not defined
The Somevariableinmytextfile is the first variable in that file.
My question:
Do I have to define every variable in the txt file, in order to get rid of this error? If not, what shall I do? I'm very new at Python. This is my first program.
Upvotes: 2
Views: 571
Reputation: 4708
The error is eval
complaining that the contents of value_string
have no meaning as a whatever-it-is.
The real error is using eval
at all. (A good post on the pitfalls can be found here.) You don't even need to eval
here - leaving value_string
as the string the regex gave you will be just fine.
Sample thefile.txt
:
foo=bar
baz=42
quux=import os; os.shutdown()
foo
, Python complains that bar
isn't defined. (Simple.)bar
, Python gives you an int
instead of a str
. (No real problem...)quux
, Python shuts down your computer. (Uh oh!)eval
You want a string value, correct? The regex already gives you a string!
varname = m.group("varname")
value = m.group("value")
print value
if varname == "THISVARIABLE":
mypythonvariable = value # You meant = instead of ==?
Upvotes: 1
Reputation: 47784
eval throws the error, the value_string
's value (which should be a variable) needs to be defined before use.
Upvotes: 0
Reputation: 5289
You get the error because a line in your thefile.txt file:
TEST = ABC
will be evaluated in python as TEST will be assigned to a value of variable ABC but you have no ABC defined.
You could make a dictionary to store your value pairs... this will work with string values:
variables = {}
accepted = ['THISVARIABLE', 'ANOTHERONE']
...
if varname in accepted:
variables[varname]=value
Upvotes: 0