如何访问当前的执行模块?

时间:2019-06-27 16:56:31

标签: 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)
…

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

1 个答案:

答案 0 :(得分:0)

如果您已经具有访问正确的有效函数和数据的方法,为什么不只将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或什至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
相关问题