Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute a string containing Python code in Python?

How do I execute a string containing Python code in Python?

like image 671
hekevintran Avatar asked Mar 31 '09 16:03

hekevintran


People also ask

How do you find something in a string in Python?

String find() in Python Just call the method on the string object to search for a string, like so: obj. find(“search”). The find() method searches for a query string and returns the character position if found. If the string is not found, it returns -1.

How code is executed in Python?

Python code is translated into intermediate code, which has to be executed by a virtual machine, known as the PVM, the Python Virtual Machine. This is a similar approach to the one taken by Java. There is even a way of translating Python programs into Java byte code for the Java Virtual Machine (JVM).


1 Answers

For statements, use exec(string) (Python 2/3) or exec string (Python 2):

>>> mycode = 'print "hello world"' >>> exec(mycode) Hello world 

When you need the value of an expression, use eval(string):

>>> x = eval("2+2") >>> x 4 

However, the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.

like image 77
Brian Avatar answered Sep 21 '22 15:09

Brian