exec() overview
The exec() function executes either a string-based expression or a compiled code object. To make code executable use the compile() function. The exec() function can execute block code.
Please be aware that passing user input to the exec() function is considered a security risk. To mitigate the risk, restrict the use of available methods and variables in exec().
exec() using string-based code
To execute a string containing Python code, use the exec() function and simply pass the string as first argument.
# exec() - execute string-based code
myCode = 'print("hello world")'
exec(myCode)
The string is executed and the print() function in the string prints "hello world".
hello world
exec() using compiled code
The compile() function returns a code object. Pass the code object to the exec() function to execute the code.
# exec() using compiled code
myCode = 'number1 = 1 \nnumber2 = 4 \nresult = number1 + number2\nprint(result)'
# compile code
compiledCode = compile(myCode, 'null', 'exec')
# execute compiled code
exec(compiledCode)
The code is compiled and the code object is passed to the exec() function to be executed. The result is printed.
5
exec() syntax
The syntax of the exec() function is:
exec(object, globals=None, locals=None)
exec() arguments
The exec() function takes between 1 and 3 arguments. The first argument is the string or code object to be executed. This argument is required.
The globals and locals arguments are optional. They can be used to modify global and local variables.
exec() return values
The exec() function returns None. The code is executed and can be used to print the result.
related functions
Releated functions are the eval() function
The eval() function evaluates a single expression.
The compile() function is used to compile code before it can be executed by the exec() function.