[英]Python equivalent of lua's loadfile
In lua there is a function called loadfile
, this function allows the program to parse a .lua file into the current project. 在lua中,有一个名为loadfile
的函数,该函数允许程序将.lua文件解析为当前项目。 All the functions and variables work as if they were written in the same file. 所有函数和变量的工作方式就像写在同一文件中一样。
This is useful for loading plugins. 这对于加载插件很有用。 I am trying to port a telegram bot over to python but cannot find a function that allows me to load a .py file and have the functions be in the context of the file. 我正在尝试将电报Bot移植到python,但是找不到允许我加载.py文件并使该函数处于文件上下文中的函数。
I have tried python's execfile
and importing the file but that doesn't allow for the functions of the loaded file to be in scope of the initial file. 我已经尝试了python的execfile
并导入了文件,但这不允许已加载文件的功能在初始文件的范围内。
(ie fileA.py loads fileB.py. fileA has function "doThis". fileB can't access "doThis" using execfile) (即fileA.py加载fileB.py。fileA具有功能“ doThis”。fileB无法使用execfile访问“ doThis”)
How can I achieve the same thing in python as loadfile for lua? 我如何在python中实现与lua的loadfile相同的功能?
I am using python 2 我正在使用python 2
You generally shouldn't do this, since wildcard imports can make code harder to debug, but: 通常不应该这样做,因为通配符导入会使代码更难以调试,但是:
from other_module import *
This imports everything defined in other_module
into the current module's global namespace. 这other_module
定义的other_module
导入到当前模块的全局名称空间中。 It's not exactly the same, but it's as close as you'll get. 它并不完全相同,但是尽你所能。
execfile("other_module.py", globals())
is very similar, except it won't cache the module in sys.modules
. 与之非常相似,只是它不会将模块缓存在sys.modules
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.