簡體   English   中英

如何在 Python 的另一個文件中打印使用某個 function 的文件路徑?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM