Find path to currently running file

后端 未结 8 1908
礼貌的吻别
礼貌的吻别 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:01

    The directory of the script which python is executing is added to sys.path This is actually an array (list) which contains other paths. The first element contains the full path where the script is located (for windows).

    Therefore, for windows, one can use:

    import sys
    path = sys.path[0]
    print(path)
    

    Others have suggested using sys.argv[0] which works in a very similar way and is complete.

    import sys
    path = os.path.dirname(sys.argv[0])
    print(path)
    

    Note that sys.argv[0] contains the full working directory (path) + filename whereas sys.path[0] is the current working directory without the filename.

    I have tested sys.path[0] on windows and it works. I have not tested on other operating systems outside of windows, so somebody may wish to comment on this.

提交回复
热议问题