我有脚本调用其他脚本文件,但我需要获得当前在进程中运行的文件的文件路径。
例如,假设我有三个文件。使用execfile:
Script_1.py调用script_2.py。 反过来,script_2.py调用script_3.py。
如何从script_3.py内的代码中获得script_3.py的文件名和路径,而不必将该信息作为script_2.py的参数传递?
(执行os.getcwd()返回初始脚本的文件路径,而不是当前文件的文件路径。)
我有脚本调用其他脚本文件,但我需要获得当前在进程中运行的文件的文件路径。
例如,假设我有三个文件。使用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 os
print os.path.basename(__file__)
这将只给我们文件名。例如,如果文件的abspath是c:\abcd\abc.py,那么第二行将打印abc.py
其他回答
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
我写了一个函数,它考虑到eclipse调试器和单元测试。 它返回您启动的第一个脚本的文件夹。你可以选择指定__file__变量,但最主要的是你不必在所有调用层次结构中共享这个变量。
也许你可以处理一些我没见过的特殊情况,但对我来说是可以的。
import inspect, os
def getRootDirectory(_file_=None):
"""
Get the directory of the root execution file
Can help: http://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing
For eclipse user with unittest or debugger, the function search for the correct folder in the stack
You can pass __file__ (with 4 underscores) if you want the caller directory
"""
# If we don't have the __file__ :
if _file_ is None:
# We get the last :
rootFile = inspect.stack()[-1][1]
folder = os.path.abspath(rootFile)
# If we use unittest :
if ("/pysrc" in folder) & ("org.python.pydev" in folder):
previous = None
# We search from left to right the case.py :
for el in inspect.stack():
currentFile = os.path.abspath(el[1])
if ("unittest/case.py" in currentFile) | ("org.python.pydev" in currentFile):
break
previous = currentFile
folder = previous
# We return the folder :
return os.path.dirname(folder)
else:
# We return the folder according to specified __file__ :
return os.path.dirname(os.path.realpath(_file_))
print(__file__)
print(__import__("pathlib").Path(__file__).parent)
您所说的“当前在进程中运行的文件的文件路径”是什么意思并不完全清楚。 sys。argv[0]通常包含被Python解释器调用的脚本的位置。 查看sys文档了解更多详细信息。
正如@Tim和@Pat Notz指出的那样,__file__属性提供了对
模块所在的文件 加载,如果是从文件中加载的
我觉得这个比较干净:
import inspect
print inspect.stack()[0][1]
得到的信息与:
print inspect.getfile(inspect.currentframe())
其中[0]是堆栈中的当前帧(堆栈的顶部),[1]是文件名,在堆栈中增加到向后,即。
print inspect.stack()[1][1]
将是调用当前帧的脚本的文件名。此外,使用[-1]将使您到达堆栈的底部,即原始调用脚本。