0

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.

6
  • 1
    What are you really trying to do? Commented Mar 24, 2015 at 16:56
  • 3
    Simple answer: yes. Better answer: yes, but you probably don't actually want to. Commented 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. Commented Mar 24, 2015 at 17:00
  • A better example would be something like this. x = "def name():" x Commented 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 exec Commented Mar 24, 2015 at 17:21

2 Answers 2

3

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'")
Sign up to request clarification or add additional context in comments.

1 Comment

He can put he should be careful.
3

The dangerous but powerful exec() and eval() are what you're looking for:

What does Python's eval() do?

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

This should be a comment, not an answer.
it is a direct answer to his question. I think this should be an answer, but I don't think the question should exist.
An answer that includes only a link is not an answer here in SO. Include a code snippet to improve your answer.
@LutzHorn why? It answers the question fully and succinctly in the text, warns about the dangers of using eval, and links to more (but critically: OPTIONAL) information
It shouldn't have even been answered, there are plenty of duplicates ... stackoverflow.com/questions/1015142/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.