首页 > 解决方案 > 使用 eval 和 exec 访问模块之外的东西

问题描述

如果我导入一个使用execor的模块eval,是否可以让它访问主程序?

我的执行文件

def myExec(code):
    exec(code)

主文件

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

标签: pythonpython-3.xexeceval

解决方案


是的!

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

myExec.py:

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

主要.py:

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

推荐阅读