我有脚本调用其他脚本文件,但我需要获得当前在进程中运行的文件的文件路径。
例如,假设我有三个文件。使用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()返回初始脚本的文件路径,而不是当前文件的文件路径。)
当前回答
最简单的方法是:
在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]返回<字符串>。
其他回答
您所说的“当前在进程中运行的文件的文件路径”是什么意思并不完全清楚。 sys。argv[0]通常包含被Python解释器调用的脚本的位置。 查看sys文档了解更多详细信息。
正如@Tim和@Pat Notz指出的那样,__file__属性提供了对
模块所在的文件 加载,如果是从文件中加载的
import os
os.path.dirname(__file__) # relative directory path
os.path.abspath(__file__) # absolute file path
os.path.basename(__file__) # the file name only
听起来你可能还想签出inspect模块。
__file__属性既适用于包含主要执行代码的文件,也适用于导入的模块。
见https://web.archive.org/web/20090918095828/http: / / pyref.infogami.com/__file__
获取执行脚本的目录
print os.path.dirname( inspect.getfile(inspect.currentframe()))