【问题标题】:Python command that returns location to a function将位置返回给函数的 Python 命令
【发布时间】:2018-07-08 13:09:35
【问题描述】:

我知道这听起来很愚蠢。

我正在寻找返回函数位置路径的 python 命令。很喜欢

command(np.reshape)

应该给出 np.reshape 所在文件夹的路径。我对找到整个 module(这里是 numpy)的主要位置不感兴趣,这已经被反复回答了。我需要函数本身的精确路径,就像 which 在 MATLAB 中做的那样。

【问题讨论】:

    标签: python matlab function file path


    【解决方案1】:

    相信你在找inspect.getsourcefile()

    根据文档,inspect.getsourcefile(object)

    返回对象所在的 Python 源文件的名称 定义。如果对象是内置的,这将失败并出现 TypeError 模块、类或函数。

    这是我在使用 join 函数测试时得到的结果:

    >>> import inspect
    >>> from os.path import join
    >>> inspect.getsourcefile(join)
    'C:\\Users\\ankit\\...\\Python\\Python36\\lib\\ntpath.py'
    

    【讨论】:

    • 我认为 getsourcefile() 对 getfile() 是多余的
    • 谢谢,这正是我想要的。奇怪的是,以前这里没有如此清晰地报道过。
    • @dopexxx 两者之间存在细微差别。 getfile() 会在对应的源文件不存在时返回二进制文件的路径并且不会报错。另一方面,getsourcefile() 将始终只返回源文件的路径,如果找不到,则会引发错误。
    猜你喜欢
    • 2016-10-18
    • 2012-08-09
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多