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

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

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

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

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


当前回答

__file__属性既适用于包含主要执行代码的文件,也适用于导入的模块。

见https://web.archive.org/web/20090918095828/http: / / pyref.infogami.com/__file__

其他回答

__file__

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

import os

os.path.realpath(__file__)

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

from pathlib import Path

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

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

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

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

查找Python脚本所在路径的主目录

作为已经在这里的其他答案的补充(并没有回答OP的问题,因为其他答案已经这样做了),如果你的脚本的路径是/home/gabriel/ g/ dev/ ercaguy_dotfiles /useful_scripts/cpu_logger.py,并且你希望获得该路径的主目录部分,即/home/gabriel,你可以这样做:

import os

# Obtain the home dir of the user in whose home directory this script resides
script_path_list = os.path.normpath(__file__).split(os.sep)
home_dir = os.path.join("/", script_path_list[1], script_path_list[2])

为了帮助理解这一点,下面是__file__、script_path_list和home_dir的路径。注意,script_path_list是一个路径组件列表,第一个元素是一个空字符串,因为它最初包含Linux路径的/ root dir路径分隔符:

__file__         = /home/gabriel/GS/dev/eRCaGuy_dotfiles/useful_scripts/cpu_logger.py
script_path_list = ['', 'home', 'gabriel', 'GS', 'dev', 'eRCaGuy_dotfiles', 'useful_scripts', 'cpu_logger.py']
home_dir         = /home/gabriel

来源:

Python:获取脚本所在目录的用户的主目录路径[重复]

我觉得这个比较干净:

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

得到的信息与:

print inspect.getfile(inspect.currentframe())

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

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

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