Search code examples
pythonwindowspathargv

How to Get the Path of the executing frozen script


If you are running a frozen python script (frozen using py2exe) from a directory and drive different from where the script is present, what is the best way to determine the path of the executing script?

Few solutions I have tried

inspect.getfile(inspect.currentframe())

Problem: Does not return the full path. It only returns the script name.

os.path.abspath( __file__ )

Problem: Doesn't work on Windows

os.path.dirname(sys.argv[0])

Problem: Returns empty string.

os.path.abspath(inspect.getsourcefile(way3))

Will not work if the drive is different from the pwd

os.path.dirname(os.path.realpath(sys.argv[0]))

Will not work if the drive is different from the pwd

Here is a minimal not-working example

D:\>path
PATH=c:\Python27\;c:\Users\abhibhat\Desktop\ToBeRemoved\spam\dist\;c:\gnuwin32\bin

D:\>cat c:\Users\abhibhat\Desktop\ToBeRemoved\spam\eggs.py
import os, inspect, sys
def way1():
    return os.path.dirname(sys.argv[0])

def way2():
    return inspect.getfile(inspect.currentframe())

def way3():
    return os.path.dirname(os.path.realpath(sys.argv[0]))

def way4():
    try:
        return os.path.abspath( __file__ )
    except NameError:
        return "Not Found"
def way5():
    return os.path.abspath(inspect.getsourcefile(way3))

if __name__ == '__main__':
    print "Path to this script is",way1()
    print "Path to this script is",way2()
    print "Path to this script is",way3()
    print "Path to this script is",way4()
    print "Path to this script is",way5()

D:\>eggs
Path to this script is
Path to this script is eggs.py
Path to this script is D:\
Path to this script is Not Found

Related Questions:

Note

@Fenikso's solution will work if the script resides on the same drive where you are executing but when its on a different drive, it will not work


Solution

  • Another approach which works with cxFreeze when running from another drive even using PATH:

    import sys
    
    if hasattr(sys, 'frozen'):
        print(sys.executable)
    else:
        print(sys.argv[0])
    

    From Python:

    H:\Python\Examples\cxfreeze\pwdme.py
    

    From command line:

    D:\>h:\Python\Examples\cxfreeze\dist\pwdme.exe
    h:\Python\Examples\cxfreeze\dist\pwdme.exe
    

    Using PATH:

    D:\>pwdme.exe
    h:\Python\Examples\cxfreeze\dist\pwdme.exe