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.

3
  • 1
    How does the expected input look like? Commented May 30, 2015 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. Commented May 30, 2015 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. Commented May 30, 2015 at 12:03

3 Answers 3

1

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

name = CMD[17:-1]
print(globals()[name])
Sign up to request clarification or add additional context in comments.

Comments

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...

Comments

-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.

6 Comments

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().
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.
Thanks for you quick responses. This solved my problem . PEACE!
@AnthonyProvenza this will work, but be aware that it's a bad solution that will likely give you bigger problems later on.
What sort of problems can i expect later on?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.