我有脚本调用其他脚本文件,但我需要获得当前在进程中运行的文件的文件路径。

例如,假设我有三个文件。使用execfile:

Script_1.py调用script_2.py。 反过来,script_2.py调用script_3.py。

如何从script_3.py内的代码中获得script_3.py的文件名和路径,而不必将该信息作为script_2.py的参数传递?

(执行os.getcwd()返回初始脚本的文件路径,而不是当前文件的文件路径。)


当前回答

我觉得这个比较干净:

import inspect
print inspect.stack()[0][1]

得到的信息与:

print inspect.getfile(inspect.currentframe())

其中[0]是堆栈中的当前帧(堆栈的顶部),[1]是文件名,在堆栈中增加到向后,即。

print inspect.stack()[1][1]

将是调用当前帧的脚本的文件名。此外,使用[-1]将使您到达堆栈的底部,即原始调用脚本。

其他回答

__file__

正如其他人所说。你可能还想使用os.path.realpath来消除符号链接:

import os

os.path.realpath(__file__)
import os
print os.path.basename(__file__)

这将只给我们文件名。例如,如果文件的abspath是c:\abcd\abc.py,那么第二行将打印abc.py

你可以使用inspect.stack()

import inspect,os
inspect.stack()[0]  => (<frame object at 0x00AC2AC0>, 'g:\\Python\\Test\\_GetCurrentProgram.py', 15, '<module>', ['print inspect.stack()[0]\n'], 0)
os.path.abspath (inspect.stack()[0][1]) => 'g:\\Python\\Test\\_GetCurrentProgram.py'

下面返回当前主脚本所在的路径。我用Linux、Win10、IPython和Jupyter Lab进行了测试。我需要一个解决方案,工作于本地Jupyter笔记本电脑以及。

import builtins
import os
import sys

def current_dir():
    if "get_ipython" in globals() or "get_ipython" in dir(builtins):
        # os.getcwd() is PROBABLY the dir that hosts the active notebook script.
        # See also https://github.com/ipython/ipython/issues/10123
        return os.getcwd()
    else:
        return os.path.abspath(os.path.dirname(sys.argv[0]))

如果您的脚本只包含一个文件,那么标记为最佳的建议都是正确的。

如果你想从一个可能作为模块导入的文件中找到可执行文件的名称(即传递给当前程序的python解释器的根文件),你需要这样做(让我们假设这是在一个名为foo.py的文件中):

进口检查

打印inspect.stack () [1] [1]

因为堆栈上的最后一个东西([-1])是进入堆栈的第一个东西(堆栈是LIFO/FILO数据结构)。

然后在bar.py文件中,如果你导入foo,它会打印bar.py,而不是foo.py,这将是所有这些的值:

__file__ inspect.getfile (inspect.currentframe ()) inspect.stack () [0] [1]