我需要在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()
。
答案 0 :(得分:0)
import os
import sys
def this_file():
print(os.path.realpath(__file__))
def that_file():
print(os.getcwd() + "/" + sys.argv[0])
我认为这就是你要找的东西。
答案 1 :(得分:0)
感谢@quantik和@Iguananaut(请参阅this),我找到了一个更通用的解决方案,可用于从.py和.ipynb文件调用Python函数:
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'])
from func import *
this_file()
that_file()
that_notebook()
输出:
/home/jovyan/work/calls.py
No active session found!
Are you calling me from a Python file? Try "that_file()" instead.
jovyan@c5cd7b908543:~/work$
from func import *
this_file()
that_file()
that_notebook()
输出:
/home/jovyan/work/func.py
Are you calling me from a Jupyter Notebook? Try "that_notebook()" instead.
work/calls.ipynb