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

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

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

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

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


当前回答

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

from pathlib import Path

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

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

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

其他回答

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

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

你可以使用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'
import os
os.path.dirname(__file__) # relative directory path
os.path.abspath(__file__) # absolute file path
os.path.basename(__file__) # the file name only
import os
print os.path.basename(__file__)

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

import sys
print sys.argv[0]