知道文件名:line_no,其中导入了my_module [英] know filename:line_no where an import to my_module was made

查看:72
本文介绍了知道文件名:line_no,其中导入了my_module的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模块 my_module 它是由许多文件使用以下来源(导入):

I have a module my_module that it is sourced (imported) by lots of files using:

来自my_module import *

在模块内部,我可以知道哪个文件导入了这个模块吗?

我想知道文件名:line_no导致这个导入。

Being inside the module, can I know which file imported this module ?
I would like to know the filename:line_no which made this import.

所以我要求的代码是:

my_module.py

my_module.py

print "This module is currently imported from: file:line_no = %s:%s" % what_in_here??


推荐答案

将它放在您的顶级模块代码中:

Place this in your top-level module code:

import traceback
last_frame = traceback.extract_stack()[-2]
print 'Module imported from file:line_no = %s:%i' % last_frame[:2]

您还可以使用 inspect 而不是< a href =http://docs.python.org/library/traceback.html =noreferrer> traceback

You can also use inspect instead of traceback:

import inspect
last_frame = inspect.stack()[1]
print 'Module imported from file:line_no = %s:%i' % last_frame[1:3]

这篇关于知道文件名:line_no,其中导入了my_module的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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