How do I get the path and name of the file that is currently executing?

后端 未结 29 2422
你的背包
你的背包 2020-11-22 06:43

I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.

For example, let\'s say I have th

29条回答
  •  不思量自难忘°
    2020-11-22 07:17

    I wrote a function which take into account eclipse debugger and unittest. It return the folder of the first script you launch. You can optionally specify the __file__ var, but the main thing is that you don't have to share this variable across all your calling hierarchy.

    Maybe you can handle others stack particular cases I didn't see, but for me it's ok.

    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_))
    

提交回复
热议问题