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

后端 未结 29 2927
你的背包
你的背包 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 06:51

    Here is what I use so I can throw my code anywhere without issue. __name__ is always defined, but __file__ is only defined when the code is run as a file (e.g. not in IDLE/iPython).

    if '__file__' in globals():
        self_name = globals()['__file__']
    elif '__file__' in locals():
        self_name = locals()['__file__']
    else:
        self_name = __name__
    

    Alternatively, this can be written as:

    self_name = globals().get('__file__', locals().get('__file__', __name__))
    

提交回复
热议问题