Find path to currently running file

后端 未结 8 1919
礼貌的吻别
礼貌的吻别 2020-12-01 01:35

How can I find the full path to the currently running Python script? That is to say, what do I have to do to achieve this:

$ pwd
/tmp
$ python baz.py
running         


        
8条回答
  •  星月不相逢
    2020-12-01 02:02

    Aside from the aforementioned sys.argv[0], it is also possible to use the __main__:

    import __main__
    print(__main__.__file__)
    

    Beware, however, this is only useful in very rare circumstances; and it always creates an import loop, meaning that the __main__ will not be fully executed at that moment.

提交回复
热议问题