Execute Python String inside a Python code using Python3

Question:

If I have a srting inside my Python code that looks like this:

x = "print('Hello World')"

I want to execute it as if it is like a seperate .py file. Is there something like

execute(x)
Asked By: Omar

||

Answers:

exec(x)

See the documentation

But be careful of injection vulnerabilities: if the string comes from a user, they will have the power to control your computer – e.g. something like __import__('shutil').rmtree('/') could remove a whole directory.

Answered By: theonlygusti
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.