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

例如,假设我有三个文件。使用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
os.path.dirname(os.path.realpath(__file__))

其他回答

import sys
print sys.argv[0]

我写了一个函数,它考虑到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_))

我有一个脚本,必须在windows环境下工作。 这段代码剪辑是什么我已经完成:

import os,sys
PROJECT_PATH = os.path.abspath(os.path.split(sys.argv[0])[0])

这是个很俗气的决定。但它不需要外部库,这是我的情况下最重要的事情。

最简单的方法是:

在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]返回<字符串>。

__file__

正如其他人所说。你可能还想使用os.path.realpath来消除符号链接:

import os

os.path.realpath(__file__)