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

例如,假设我有三个文件。使用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]返回<字符串>。

其他回答

__file__属性既适用于包含主要执行代码的文件,也适用于导入的模块。

见https://web.archive.org/web/20090918095828/http: / / pyref.infogami.com/__file__

import os
print os.path.basename(__file__)

这将只给我们文件名。例如,如果文件的abspath是c:\abcd\abc.py,那么第二行将打印abc.py

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

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

听起来你可能还想签出inspect模块。