如何在导入的文件中找到作为导入程序的文件的名称? [英] How do I find the name of the file that is the importer, within the imported file?

查看:81
本文介绍了如何在导入的文件中找到作为导入程序的文件的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在导入的文件中找到进口商"文件的名称?

How do I find the name of the file that is the "importer", within the imported file?

如果a.pyb.py都导入了c.py,则c.py是否可以知道导入该文件的文件名?

If a.py and b.py both import c.py, is there anyway that c.py can know the name of the file importing it?

推荐答案

在c.py的顶层(即,在任何函数或类之外),您应该能够通过运行获取所需的信息

In the top-level of c.py (i.e. outside of any function or class), you should be able to get the information you need by running

import traceback

,然后检查traceback.extract_stack()的结果.在运行顶层代码时,模块的导入器(及其递归导入器等)都在调用堆栈上.

and then examining the result of traceback.extract_stack(). At the time that top-level code is run, the importer of the module (and its importer, etc. recursively) are all on the callstack.

这篇关于如何在导入的文件中找到作为导入程序的文件的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆