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

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

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

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

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


当前回答

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

其他回答

最简单的方法是:

在script_1.py:

import subprocess
subprocess.call(['python3',<path_to_script_2.py>])

在script_2.py:

sys.argv[0]

附注:我尝试过execfile,但由于它将script_2.py作为字符串读取,sys。Argv[0]返回<字符串>。

这是我使用的,所以我可以把我的代码扔到任何地方而没有问题。__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__))

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

查找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 os
os.path.dirname(__file__) # relative directory path
os.path.abspath(__file__) # absolute file path
os.path.basename(__file__) # the file name only