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.
-
1What are you really trying to do?user1907906– user19079062015年03月24日 16:56:57 +00:00Commented Mar 24, 2015 at 16:56
-
3Simple answer: yes. Better answer: yes, but you probably don't actually want to.Eric Hughes– Eric Hughes2015年03月24日 16:59:03 +00:00Commented Mar 24, 2015 at 16:59
-
I was trying to create a program the seems like artificial intelligence (it's really not) that helps me out with my computer and can learn new things and create new functions based on what it has learned. I mean like the 'def' function, I wanted my program to be able to define new functions with the 'def' command, and the name of that definition is going to be the string.jumbi533– jumbi5332015年03月24日 17:00:06 +00:00Commented Mar 24, 2015 at 17:00
-
A better example would be something like this. x = "def name():" xjumbi533– jumbi5332015年03月24日 17:02:19 +00:00Commented Mar 24, 2015 at 17:02
-
if you are trying to write a program that can write its own code ... that is not like AI... that is AI ... and very complicated stuff... if thats not really what you are trying to do you should come up with a better way of doing this than eval and execJoran Beasley– Joran Beasley2015年03月24日 17:21:38 +00:00Commented Mar 24, 2015 at 17:21
2 Answers 2
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'")
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
7 Comments
eval, and links to more (but critically: OPTIONAL) information