[英]How to print the file path that uses the certain function in another file in Python?
我有兩個文件。 /a/a.py
和/b/b.py
在/b/b.py
中,我有一個 func foo()
。 在/a/a.py
中,我導入了 func foo()
。
我想在foo()
中添加一行來打印導入和使用這個函數的文件路徑。 在這種情況下, /a/a.py
我嘗試使用print(__file__)
但它只顯示/b/b.py
的路徑
是否有任何適用於此的 package?
由於 importlib 的工作方式,導入部分很難,但使用部分相當簡單,您可以通過使用 inspect 模塊檢查堆棧輕松獲取調用者的信息,但這僅在 Cpython 中才有可能。
從這個答案中采用
import inspect
def a():
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
print('caller name:', calframe[1][3])
print('caller file:', calframe[1][1])
def b():
a()
b()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.