Using a text file to receive a string for a variable in Python, without defining it -
i have text file in there several variables. of them used in bash script of mine, i'd use same text file python script. lines not formatted python, want script ignore. formatted, want script check , if it's variable i'm looking - 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 # if variables name thisvariable, value: if varname == "thisvariable": mypythonvariable == value
i'm getting following error:
nameerror: name 'somevariableinmytextfile' not defined
the somevariableinmytextfile first variable in file.
my question:
do have define every variable in txt file, in order rid of error? if not, shall do? i'm new @ python. first program.
the error eval
complaining contents of value_string
have no meaning whatever-it-is.
the real error using eval
@ all. (a post on pitfalls can found here.) you don't need eval
here - leaving value_string
string regex gave just fine.
the problem present approach
sample thefile.txt
:
foo=bar baz=42 quux=import os; os.shutdown()
- when parsing
foo
, python complainsbar
isn't defined. (simple.) - when parsing
bar
, python givesint
instead ofstr
. (no real problem...) - when parsing
quux
, python shuts down computer. (uh oh!)
why don't need eval
you want string value, correct? regex gives string!
varname = m.group("varname") value = m.group("value") print value if varname == "thisvariable": mypythonvariable = value # meant = instead of ==?
Comments
Post a Comment