打印Python中函数定义和调用的地址

Printing the address of the function definition and calls in Python

我需要在 Python 中有几个函数(任一变体)来查找和打印它们存储或调用的文件的名称。例如,考虑以下函数存储在此地址:/my/py/func.py:

def this_file():
# print the address of this file
print('this function is stored at %s' % this_file_address)

def that_file():
# print the address of the file that is calling this function
print('this function is called form a file at %s' % that_file_address)

我有一段代码存储在/my/py/calls.py:

from func import *
this_file()
that_file()

现在,我希望通过上述函数打印以下内容:

/my/py/func.py 
/my/py/calls.py

如何编写这些函数?


编辑#1 从 Jupyter 笔记本调用 that_file() 似乎应该以不同的方式处理。

import os                                                                                                                                                           
import sys
def this_file():
         print(os.path.realpath(__file__))

def that_file():
        print(os.getcwd() + "/" + sys.argv[0])

我想这就是您要找的。

感谢 @quantik and @Iguananaut (see this),我可以找到一个更通用的解决方案,适用于从 .py 和 .ipynb 文件调用 Python 函数:

func.py

内容:
import os.path                                                                                                                               
import sys
import urllib.request
import json

def this_file():
    # prints the address of this file
    print(__file__)
    return __file__


def that_file():
    # prints the address of the file that is calling this function
    if sys.argv[0][-21:]=='ipykernel_launcher.py':
        print('Are you calling me from a Jupyter Notebook? Try "that_notebook()" instead.')
        return False
    else:
        print(os.getcwd() + "/" + sys.argv[0])
        return os.getcwd() + "/" + sys.argv[0]


def that_notebook(base_url='http://127.0.0.1:8888'):
    # prints the address of the notebook that is calling this function
    ## read more about Jupyter APIL: https://github.com/jupyter/jupyter/wiki/Jupyter-Notebook-Server-API

    # See if the url is correct
    try:
        sessions = json.load(urllib.request.urlopen(base_url+'/api/sessions'))
    except:
        print('Oops! %s is an invalid URL.' % (base_url+'/api/sessions'))
        return False

    # See if there is any active session
    if len(sessions) == 0:
        print('No active session found!')
        print('Are you calling me from a Python file? Try "that_file()" instead.')
        return False

    # In case of multiple active sessions, only print the most recently 
    latest=max([s['kernel']['last_activity'] for s in sessions])
    for s in sessions:    
        if s['kernel']['last_activity']==latest:
            print(s['path'])
            return(s['path'])

calls.py

内容:
from func import *
this_file()
that_file()
that_notebook()
输出:

python calls.py

/home/jovyan/work/calls.py
No active session found!
Are you calling me from a Python file? Try "that_file()" instead.
jovyan@c5cd7b908543:~/work$

calls.ipynb

内容:
from func import *
this_file()
that_file()
that_notebook()
输出:

calls.ipynb

/home/jovyan/work/func.py
Are you calling me from a Jupyter Notebook? Try "that_notebook()" instead.
work/calls.ipynb