【问题标题】:How to get the path of a function in Python?如何在 Python 中获取函数的路径?
【发布时间】:2018-06-04 04:51:18
【问题描述】:

我想在 Python 中获取一个函数的文件路径。

怎么做?

例如,

import keras.backend as K
y = K.resize_images(x, 2, 2, 'channels_last')
path = function(K.resize_images)
print(path)
#C:\Program Files\Python36\Lib\site-packages\keras\backend\tensorflow_backend.py

谢谢。

【问题讨论】:

标签: python


【解决方案1】:

您可以为此目的使用inspect module 中的getfile() 函数。

例如,给定以下文件:

inspect-example.py

#!/usr/bin/python

import os
import inspect
import external_def

def foo():
  pass
    
print(os.path.abspath(inspect.getfile(foo)))
print(os.path.abspath(inspect.getfile(external_def.bar)))

external_def.py

def bar():
  pass

执行inspect_example.py 会产生以下输出:

$ python inspect-example.py
/home/chuckx/code/stackoverflow/inspect-example.py
/home/chuckx/code/stackoverflow/external_def.py

【讨论】:

  • 它有效。谢谢你,查克。对于我的示例,代码是: print(os.path.abspath(inspect.getfile(K.resize_images)))
【解决方案2】:

如果你想获取包含函数的文件的路径可以试试下面的代码,注意:这个代码只有在对象类型是'function'的情况下才有效

def get_path(func):  
     if type(func).__name__ == 'function' : 
         return func.__code__.co_filename
     else: 
         raise ValueError("'func' must be a function") 

【讨论】:

    【解决方案3】:

    使用 Python 路径类:

    Path('.').resolve()
    

    【讨论】:

    • 这里说的不是源码位置,不是解释器进程的cwd位置。
    猜你喜欢
    • 2014-01-19
    • 2017-05-20
    • 2022-11-03
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2020-05-28
    相关资源
    最近更新 更多