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

后端 未结 29 2789
你的背包
你的背包 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:18

    The suggestions marked as best are all true if your script consists of only one file.

    If you want to find out the name of the executable (i.e. the root file passed to the python interpreter for the current program) from a file that may be imported as a module, you need to do this (let's assume this is in a file named foo.py):

    import inspect

    print inspect.stack()[-1][1]

    Because the last thing ([-1]) on the stack is the first thing that went into it (stacks are LIFO/FILO data structures).

    Then in file bar.py if you import foo it'll print bar.py, rather than foo.py, which would be the value of all of these:

    • __file__
    • inspect.getfile(inspect.currentframe())
    • inspect.stack()[0][1]

提交回复
热议问题