How to Execute a String Containing Python Code


  • exec() function executes Python statements stored as a String or a code object.
  • The function can accept large blocks of code. In contrast, eval() function only accepts a single expression.
  • The returned value of exec() function is always none.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# Execute python codes
exec('print("Hello World")')

# Take user's input and execute it
codes = input('Please input your codes:')
exec(codes)

Output:

Hello World

Please input your codes: # here we input: print 'Python is great!'
Python is great!

Tips

When using exec() and input() functions together in your codes, you need be careful. It is possible that users’ input can be converted to a command line. In this context, it will cause serious security problem. For example, in Unix system, if the user input “rm -rf *.txt” and this statement is taken by input() function and then executed by exec() function, all txt files in the directory of python file will be deleted.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement