【问题标题】:Printing the address of the function definition and calls in Python在 Python 中打印函数定义和调用的地址
【发布时间】:2018-03-05 00:28:54
【问题描述】:

我需要在 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() 似乎应该以不同的方式处理。

【问题讨论】:

    标签: python filenames


    【解决方案1】:
    import os                                                                                                                                                           
    import sys
    def this_file():
             print(os.path.realpath(__file__))
    
    def that_file():
            print(os.getcwd() + "/" + sys.argv[0])
    

    我认为这就是您要寻找的。

    【讨论】:

    • 感谢您的快速和有用的回答。您的解决方案在普通 Python 脚本中运行良好,但在 Jupyter 笔记本中却不行。例如,如果我从 .ipynb 文件中调用它们,我会得到以下信息:/home/jovyan/work/func.py /home/jovyan/work//opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py 似乎 argv[0] 总是指向 /opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py
    【解决方案2】:

    感谢@quantik@Iguananaut(请参阅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
    

    【讨论】:

    • **已知错误:**由于某些原因,urllib.request.urlopen 无法从任何端口读取,除非是 8888。这可能是防火墙问题。
    猜你喜欢
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    相关资源
    最近更新 更多