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

例如,假设我有三个文件。使用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]将使您到达堆栈的底部,即原始调用脚本。

其他回答

p1.py:

execfile("p2.py")

p2.py:

import inspect, os
print (inspect.getfile(inspect.currentframe())) # script filename (usually with path)
print (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory

我对__file__使用了这种方法 os.path.abspath (__file__) 但是有一个小技巧,它返回。py文件 当代码第一次运行时, 下一个运行的名称为*。佩克文件 所以我选择了: inspect.getfile (inspect.currentframe ()) 或 .f_code.co_filename sys._getframe ()

由于Python 3是相当主流的,我想包含一个pathlib的答案,因为我相信它现在可能是一个更好的访问文件和路径信息的工具。

from pathlib import Path

current_file: Path = Path(__file__).resolve()

如果你正在寻找当前文件的目录,只需在Path()语句中添加.parent即可:

current_path: Path = Path(__file__).parent.resolve()

这是我使用的,所以我可以把我的代码扔到任何地方而没有问题。__name__总是被定义,但__file__只在代码作为文件运行时才被定义(例如,不在IDLE/iPython中)。

if '__file__' in globals():
    self_name = globals()['__file__']
elif '__file__' in locals():
    self_name = locals()['__file__']
else:
    self_name = __name__

或者,这可以写成:

self_name = globals().get('__file__', locals().get('__file__', __name__))
import os
os.path.dirname(os.path.abspath(__file__))

不需要检查或任何其他图书馆。

当我必须导入一个脚本(从与执行脚本不同的目录)时,这对我有用,它使用了与导入脚本位于同一文件夹中的配置文件。