简体   繁体   English

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

[英]Printing the address of the function definition and calls in Python

I need to have a couple of functions in Python (either variation) to find and print the name of the file they are stored or called from.我需要在 Python 中使用几个函数(任一变体)来查找和打印存储或调用它们的文件的名称。 For example, consider the following functions are stored in at this address: /my/py/func.py :例如,考虑以下函数存储在此地址: /my/py/func.py

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

and

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)

And I have a piece of code stored in /my/py/calls.py :我有一段代码存储在/my/py/calls.py

from func import *
this_file()
that_file()

Now, I want the followings to be printed by the above functions:现在,我希望通过上述功能打印以下内容:

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

How can I write these functions?我该如何编写这些函数?


Edit #1 It seems calling that_file() from Jupyter notebooks should be handled differently.编辑 #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])

I think this is what you're looking for.我想这就是你要找的。

Thanks to @quantik and @Iguananaut (see this ), I could find a more general solution that works for calling Python functions from .py and .ipynb files:感谢@quantik@Iguananaut (见这个),我可以找到一个更通用的解决方案,它适用于从 .py 和 .ipynb 文件调用 Python 函数:

func.py功能文件

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

calls.py调用.py

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

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调用.ipynb

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

calls.ipynb调用.ipynb

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM