0

So basically, I have a python program but there's a point in which I need help. When the user input the variable name, I want it to print the variable value, not the variable name, even if the variable doesn't exist. This is what I've currently got:

    CMD = input(">>>>  ")

    if CMD[0:17] == "console.printVar(" and CMD[-1:] == ")" and CMD[-2:]!="')":
    try:
        CMD[13:-1]
    except NameError:
        print("Variable "+CMD[13:1]+" Not defined")
        Main()
    else:
        print(CMD[17:-1])
        Main()

Oh, and just in case it's not clear, i'm sort of working on a coding language sort of thing.

  • 1
    How does the expected input look like? – Martin Preusse May 30 '15 at 11:47
  • 1
    Why don't you store the "variables" in a dictionary, so you can easily access them by name (this is basically what Python does, under the hood)? E.g. `variables[CMD[13:-1]]`. You can use `variables.get(..., default)` or `... in variables` to deal with missing keys. – jonrsharpe May 30 '15 at 12:00
  • Oh, and if you're using recursion rather than iteration to keep your program looping, note that a long-running interaction will hit the [limit](https://docs.python.org/2/library/sys.html#sys.getrecursionlimit). – jonrsharpe May 30 '15 at 12:03

3 Answers3

1

To get the value of a global variable by name, use the globals() dictionary:

name = CMD[17:-1]
print(globals()[name])
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
1

You can get the local (function's) scope as a dict with locals() and the global (module's) scope as a dict with globals(). Now you may want to read a bit more about parsing, AST etc...

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
-1

You can just call eval(CMD[17:-1]).

However, this evaluates more than just variable names, so be careful that the user cannot do anything malicious with your code.

jsfan
  • 1,373
  • 9
  • 21
  • `eval()` is usually not the right solution in Python - there are dedicated ways to get to almost anything at runtime -, and this case (passing user inputs) is obviously the one where you _really_ _dont_ want to use `eval()`. – bruno desthuilliers May 30 '15 at 11:54
  • I agree that it's quick and dirty. Of course, there are better ways. However, depending on the context, quick and dirty might be good enough. Thus, my suggestion including a warning. – jsfan May 30 '15 at 11:58
  • Thanks for you quick responses. This solved my problem . PEACE! –  May 30 '15 at 12:08
  • 1
    @AnthonyProvenza this will *work*, but be aware that it's a **bad solution** that will likely give you bigger problems later on. – jonrsharpe May 30 '15 at 12:08
  • What sort of problems can i expect later on? –  May 30 '15 at 12:12
  • @AnthonyProvenza see also http://stackoverflow.com/q/1832940/3001761. Note that you need to add `@` to the start of names to notify the user you're commenting. – jonrsharpe May 30 '15 at 12:22