简体   繁体   English

如何在Python中获取调用者脚本的完整路径

[英]How to get the caller script full path in Python

I have a caller script /home/x/a/a.py that uses module /home/x/b.py 我有一个使用模块/home/x/b.py的调用者脚本/home/x/a/a.py

Inside b.py, I want to know the full path of the caller script, ie /home/x/a/a.py. 在b.py中,我想知道调用者脚本的完整路径,即/home/x/a/a.py。 How can I get that? 我该怎么办?

I looked at How to get the caller script name but it only gave me the script name which is a.py 我看了看如何获得调用者脚本名称,但它只给了我一个名为a.py的脚本名称。

A very simplified version of what happens (for the CPython interpreter): 发生的事情的非常简化的版本(对于CPython解释器):

Every time a method is called in Python a "frame" is added to the stack, after a method returns something the interpreter pops the last frame from the stack and continues execution of the previous frame with the return value injected in place of the method call 每次在Python中调用方法时,都会在堆栈中添加一个“框架”,方法返回结果后,解释器会弹出堆栈中的最后一帧,并继续执行前一帧,并使用返回值代替方法调用

To get the previous frame you can call sys._getframe(1) (0 would get the current frame, 1 gets the previous frame). 要获取前一帧,可以调用sys._getframe(1) (0将获取当前帧,1将获取前一帧)。 The inspect module provides a method getframeinfo that returns some useful information about the frame including the filename. 检查模块提供了一种getframeinfo方法,该方法返回有关框架的一些有用信息,包括文件名。 This can be combined like so 可以像这样组合

import inspect
import sys

def foo():
    print('Called from', inspect.getframeinfo(sys._getframe(1)).filename)

Whenever foo is called it will print the filename of the calling method 每当调用foo ,它将打印调用方法的文件名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM