使用 Python3 在 Python 代码中执行 Python 字符串

Oma*_*mar 0 python python-3.x

如果我的 Python 代码中有一个如下所示的 srting:

x = "print('Hello World')"
Run Code Online (Sandbox Code Playgroud)

我想像执行一个单独的 .py 文件一样执行它。有没有类似的东西

execute(x)
Run Code Online (Sandbox Code Playgroud)

the*_*sti 5

exec(x)
Run Code Online (Sandbox Code Playgroud)

查看文档

但要小心注入漏洞:如果字符串来自用户,他们将有权控制您的计算机 - 例如,__import__('shutil').rmtree('/')可以删除整个目录。