Is there a way to take a string and use it as a command in Python?
Something similar to the example shown below.
x = "import time"
x
time.sleep(1)
I know the example above won't work, that is just to help you understand what I am trying to do.
Is there a way to take a string and use it as a command in Python?
Something similar to the example shown below.
x = "import time"
x
time.sleep(1)
I know the example above won't work, that is just to help you understand what I am trying to do.
The dangerous but powerful exec() and eval() are what you're looking for:
Running Python code contained in a string
Use exec()(its a function in Python 3.x, but a statement in 2.x) to evaluate statements, so:
exec('print(5)') # prints 5.
and eval() to evaluate expressions:
x=5 #prints 5
eval('x+1') #prints 6
You can use eval.eval() is used to evaluate expression, If you want to execute a statement, use exec()
See example for eval:
def fun():
print "in fun"
eval("fun()")
x="fun()"
eval(x)
See example for exec.
exec("print 'hi'")