我有脚本调用其他脚本文件,但我需要获得当前在进程中运行的文件的文件路径。
例如,假设我有三个文件。使用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]返回<字符串>。
其他回答
试试这个,
import os
os.path.dirname(os.path.realpath(__file__))
获取执行脚本的目录
print os.path.dirname( inspect.getfile(inspect.currentframe()))
__file__
正如其他人所说。你可能还想使用os.path.realpath来消除符号链接:
import os
os.path.realpath(__file__)
我写了一个函数,它考虑到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_))
如果您的脚本只包含一个文件,那么标记为最佳的建议都是正确的。
如果你想从一个可能作为模块导入的文件中找到可执行文件的名称(即传递给当前程序的python解释器的根文件),你需要这样做(让我们假设这是在一个名为foo.py的文件中):
进口检查
打印inspect.stack () [1] [1]
因为堆栈上的最后一个东西([-1])是进入堆栈的第一个东西(堆栈是LIFO/FILO数据结构)。
然后在bar.py文件中,如果你导入foo,它会打印bar.py,而不是foo.py,这将是所有这些的值:
__file__ inspect.getfile (inspect.currentframe ()) inspect.stack () [0] [1]