首页 > 解决方案 > 如何访问当前正在执行的模块?

问题描述

我想从导入的模块访问调用环境。

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)
…

创建对(新)模块的引用,而不是正在运行的模块,这就像创建一个新类:一个代码购买不同的环境。

标签: python-3.x

解决方案


如果您已经有一种方法可以访问正确的函数和有效的数据,为什么不直接存储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_backchild

导入的模块:

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

推荐阅读