我有脚本调用其他脚本文件,但我需要获得当前在进程中运行的文件的文件路径。
例如,假设我有三个文件。使用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()返回初始脚本的文件路径,而不是当前文件的文件路径。)
当前回答
获取执行脚本的目录
print os.path.dirname( inspect.getfile(inspect.currentframe()))
其他回答
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
import sys
print sys.argv[0]
__file__
正如其他人所说。你可能还想使用os.path.realpath来消除符号链接:
import os
os.path.realpath(__file__)
我对__file__使用了这种方法 os.path.abspath (__file__) 但是有一个小技巧,它返回。py文件 当代码第一次运行时, 下一个运行的名称为*。佩克文件 所以我选择了: inspect.getfile (inspect.currentframe ()) 或 .f_code.co_filename sys._getframe ()
你可以使用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'