python-3.x - 如何访问当前正在执行的模块?
问题描述
我想从导入的模块访问调用环境。
import child
…
def test(xxx):
print("This is test " + str(xxx))
child.main()
…
现在在孩子身上:
import inspect
def main():
caller = inspect.currentframe().f_back
caller.f_globals['test']("This is my test")
这行得通,但它并不花哨。在课堂上使用时是否有像“自我”这样的简化?这个想法是: caller.test('abc') 代替。
一种将调用者作为参数传递的选项,例如:child.main(self),但是 self 在此上下文中不可用。
Python 只加载一个模块的一个版本,所以被这个想法所吸引:
import sys
myself=sys.modules[__name__]
a 然后将自己发送给孩子:
…
child.main(myself)
…
创建对(新)模块的引用,而不是正在运行的模块,这就像创建一个新类:一个代码购买不同的环境。
解决方案
如果您已经有一种方法可以访问正确的函数和有效的数据,为什么不直接存储f_globals
在包装类的实例中,然后从实例中调用事物,就好像它们是未绑定的属性一样?您可以使用类本身,但使用实例可确保从导入文件中获取的数据在创建对象时有效。然后您可以按照您想要的方式使用点运算符进行访问。这是你的child
文件:
import inspect
class ImportFile:
def __init__(self, members):
self.__dict__.update(members)
def main():
caller = inspect.currentframe().f_back
imported_file = ImportFile(caller.f_globals)
imported_file.test("This is my test")
输出:
This is test This is my test
诚然,我没有你的设置,重要的是你试图从中提取的模块,所以很难确认这是否对你有用,即使它对我有用,但我认为你也可以使用你的方法调用或什至在你正在导入的模块内部时main
,你仍然在你从 inside访问的框架上。globals()
inspect.getmembers()
f_back
child
导入的模块:
import child
def test(xxx):
print("This is test " + str(xxx))
child.main(globals())
孩子:
import inspect
class ImportFile:
def __init__(self, members):
self.__dict__.update(members)
def main(caller):
imported_file = ImportFile(caller)
imported_file.test("This is my test")
输出:
This is test This is my test
推荐阅读
- apache-spark - 在集群中使用 pyspark 运行时出现 Apache spark 错误
- flutter - 颤振医生:无法更改下一次执行调用的配置文件:没有这样的文件或目录
- json - json_encode 带有特殊字符和空格的字符串
- r - Igraph 错误中的 Mark.groups:选择了未知的 vertex.names
- reactjs - react如何在打印页面中显示自定义的页码
- java - 如何使Horizontal Recyclerview无限滚动而不滚动回第一项
- ios - swift 5,如何在collectionView中加载超过7000〜图像?
- python - 高斯拟合函数异常
- javascript - 如何进入从 json 获得的数组?
- k3s - 0/1 个节点可用:1 个节点没有用于请求的 pod 端口的空闲端口