Using a text file to receive a string for a variable in Python, without defining it
Question: 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.


Answer: 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](http://me.veekun.com/blog/2012/03/24/on-principle/).) **You don't
even need to`eval` here** \- leaving `value_string` as the string the regex
gave you will be _just fine_.

# The problem with the present approach

Sample `thefile.txt`:

    
    
    foo=bar
    baz=42
    quux=import os; os.shutdown()
    

  * When parsing `foo`, Python complains that `bar` isn't defined. (Simple.)
  * When parsing `bar`, Python gives you an `int` instead of a `str`. (No real problem...)
  * When parsing `quux`, Python shuts down your computer. (_Uh oh!_)

# Why you don't need `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 ==?
    

