是否有 __file__ 的版本在函数中使用时会获取使用该库的文件的名称?

Is there a version of __file__ that when used in a function, will get the name of the file that uses the library?

所以,作为一个笑话,我为 python 编写了一个 goto 版本,我想将其用作一个库。我为它写的函数如下

def goto(loc):
  exec(open(__file__).read().split("# "+str(loc))[1],globals())
  quit()

这适用于它位于使用 goto 的文件中的情况,例如:

def goto(loc):
  exec(open(__file__).read().split("# "+str(loc))[1],globals())
  quit()


# hi
print("test")
goto("hi")

但是,如果我在另一个文件中导入 goto,它就不会像

__file__

将始终 return 包含函数的文件,而不是使用它的文件。是否有等效的文件允许我导入一个包含 goto 函数的文件并拥有有用吗?

是的,如果您检查调用堆栈就可以:

import inspect

def goto():
    try:
        frame = inspect.currentframe()
        print(frame.f_back.f_globals['__file__'])
    finally:
        # break reference cycles
        # https://docs.python.org/3.6/library/inspect.html#the-interpreter-stack
        del frame

goto()

请注意,调用堆栈实际上 python 依赖于实现——因此对于某些 python 解释器,这可能实际上不起作用...

当然,我还向您展示了如何获取调用者的全局变量(locals 可以通过 frame.f_back.f_locals 找到,以满足您的所有 execing 需求)。

另请注意 it looks like you can implement a jump command 通过写入框架的 f_lineno -- 这可能是实现 goto 的更好方法。不过我从来没有这样做过,所以我无法就如何实际编写代码向您提供真正的建议:-)