0

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)
Omar
  • 297
  • 5
  • 16
  • You can use `exec()` see https://docs.python.org/3/library/functions.html#exec. Also see this thread for a discussion on the topic, and a comparison of the functions `eval` and `exec`. – ChrisOram Jul 29 '22 at 09:08
  • Please have a look at [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/q/261592/3929826)! – Klaus D. Jul 29 '22 at 09:09
  • Why `exec()` should be avoided: https://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided – Jerry Jul 29 '22 at 09:15
  • Depending on your use case, https://github.com/alexmojaki/python_runner might be good for you – Alex Hall Jul 29 '22 at 09:48

1 Answers1

5
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.

The Thonnu
  • 3,578
  • 2
  • 8
  • 30
theonlygusti
  • 11,032
  • 11
  • 64
  • 119