【问题标题】:Access things outside of module with eval and exec使用 eval 和 exec 访问模块之外的东西
【发布时间】:2021-08-08 22:38:57
【问题描述】:

如果我导入一个使用exec 或eval 的模块,是否可以授予它访问主程序的权限?

myExec.py

def myExec(code):
    exec(code)

main.py

import myExec
def test():
    print("ok")
myExec.myExec("test()")

【问题讨论】:

  • 不要将文件命名为 exec,因为您现在在导入时会覆盖内置文件
  • 如果您更改模块名称,您还需要更改其中的函数在main.py 中的使用方式——因此您上次的编辑不完整。

标签: python python-3.x exec eval


【解决方案1】:

是的!

exec 有一些可选参数,全局和局部。这些基本上以字典的形式告诉它允许使用哪些全局变量和局部变量。调用 globals() 或 locals() 函数会返回包含您从中调用的所有全局和局部变量的字典,因此您可以使用:

myExec.py:

def myExec(code, globals_=None, locals_=None):  # the trailing underscore is so that there are no name conflicts
    exec(code, globals_, locals_)

main.py:

import myExec
def test():
    print("ok")
myExec.myExec("test()", globals())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    相关资源
    最近更新 更多