Warm tip: This article is reproduced from serverfault.com, please click

How can I convert string to source code in python?

发布于 2017-05-09 19:37:15

As you see, ifinner is a string, so if I just write after if, always will be true. What can i do, to concert it to source code?

    x=2
    ifinner = "x==3"
    if ifinner:
        print("Yeah")
    else:
        print("It works!")
Questioner
Turcsi
Viewed
0
Laurent LAPORTE 2017-05-10 03:41:30

You can use eval() function to evaluate Python source code.

Quoting the documentation:

eval(expression, globals=None, locals=None)

The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.