How to Execute a String Containing Code in Python
In this quick tutorial, we'll show how to execute string containing Python code in Python and Jupyter.
In other words we will run Python code dynamically from another Python code. We'll first look into executing code with statements, then code with expressions, and finally we will cover Jupyter Notebooks.
Step 1: Execute a String statements in Python
We can use method exec
to execute statement stored as a string in Python code.
Below we can find simple example of executing string as code in Python with exec()
:
some_code = 'print ("Hello World!")'
exec(some_code)
The result is printing the:
Hello World!
More information about method exec()
can be found in the official documentation: exec - Built-in Functions
The method is described as:
This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs).
The parameters of the method exec
:
- object - Either a string or a code object
- globals (optional) - a dictionary
- locals (optional)- a mapping object
The parameters globals
and locals
allow a user to specify what global and local functions / variables are available.
Executing or evaluating could be dangerous in some cases. Use it only if you are sure what you are doing.
Step 2: Execute a String expression in Python
To execute strings containing Python expressions we can use method - eval
. Method eval
takes string containing expression and evaluate it as Python code:
x = 1
eval('x+1')
result:
2
The official documentation can be found on this link: eval - Built-in Functions.
The method is described as:
The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace.
Difference between `eval` and `exec` is that - `eval('x=2')` - is returning an error while `exec('x=2')` works fine.
Step 3: Execute a String code in Jupyter Notebook
If you need to execute dynamically Python code which is evaluated from a string in Jupyter Notebook we can use the same methods:
exec
eval
Both can read code from another file or Jupyter Notebook and execute it:
x = 1
eval('x+1')
result:
2
Step 4: Execute a Multiline String code in Python
Finally let's see how we can execute multiline string as a Python code with method exec
in simple example:
some_code = """
x = 0
if x == False :
print("x Is False")
else :
print("x Is True")
"""
exec(some_code)
the result is printed on the Python console:
x Is False
Conclusion
In this article, we looked at different solutions for executing and evaluating string expressions or statements as Python code.
We focused on executing in these code examples, but evaluating is very similar and simpler.