python - 使用 eval 和 exec 访问模块之外的东西
问题描述
如果我导入一个使用exec
or的模块eval
,是否可以让它访问主程序?
我的执行文件
def myExec(code):
exec(code)
主文件
import myExec
def test():
print("ok")
myExec.myExec("test()")
解决方案
是的!
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())
推荐阅读
- html - 为什么我的 margin-top 会将整个部分向下移动?
- r - R:计算组内百分比
- api - curl 使用 PHP 问题 - 如何通过更改 url 调用多个 api 请求
- http - https中的密钥
- javascript - 在 JavaScript 中将 100 除以相等的百分比
- javascript - 如何将动态 URL 添加到制表单元格?
- android - 我怎样才能创建一个看起来像这样的导航标题组件?
- python - 在流式传输期间在循环中创建无限对象是否有效?
- typescript - Vuex 商店在 created() 方法中返回 [__ob__: Observer] 而不是字符串
- javascript - Laravel 8 将数据从刀片传递到 Vue 3