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)
Answers:
exec(x)
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.
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)
exec(x)
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.