python-3.x - 如何访问当前正在执行的模块?

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

import child
…
def test(xxx):
   print("This is test " + str(xxx))

child.main()
…

现在 child :

import   inspect
def main():
     caller = inspect.currentframe().f_back
     caller.f_globals['test']("This is my test")

这行得通,但并不花哨。在类里面使用时是否有像“ self ”这样的简化?这个想法是做: caller.test('abc') 代替。

将调用者作为参数传递的一个选项,例如:child.main(self),但是 self 在此上下文中不可用。

Python 只加载一个模块的一个版本,因此,受到这个想法的诱惑:

import sys
myself=sys.modules[__name__]

然后将自己发送给 child :

…
child.main(myself)
…

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

最佳答案

如果您已经有了访问正确功能和数据的方法,为什么不将 f_globals 存储在包装类的实例上,然后从实例中调用事物,就好像它们是未绑定(bind)的一样特性?您可以使用类本身,但使用实例可确保在创建对象时从导入文件中获取的数据有效。然后您可以按照您想要的方式使用点运算符进行访问。这是您的文件:

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

不可否认,我没有你的设置,重要的是你试图从中提取的模块,所以很难确认这是否适合你,即使它对我有用,但我认为你也可以使用通过 globals() 或什至 inspect.getmembers() 调用 main 的方法,因为在您导入的模块中仍在您从 child 内部使用 f_back 访问的框架上。

导入的模块:

import child

def test(xxx):
  print("This is test " + str(xxx))

child.main(globals())

child :

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

https://stackoverflow.com/questions/56795665/

相关文章:

python - 如何在 Python 中使用计时器解锁条件?

datetime - Flutter:DateTime.now 不反射(reflect)手动设置的时

node.js - GCP 应用引擎 : Random pending requests for s

python - 如何在 python 中为 for 循环手动输入?

c++ - 使用 Microsoft Visual Studio 运行 C++ "hello wor

python - 如何序列化 CSR 矩阵

python-3.x - 如何在 python 中使用 opencv 读取数据矩阵代码?

python - 如何删除 seaborn 的 lmplot 函数中的图例?

laravel - 当我部署到服务器时,Laravel 项目中的 vue 组件不会更新

git - 列出与完全 merge 的分支的提交差异时如何忽略精心挑选的提交