How to Get the Path of the executing frozen script

前端 未结 3 1746
轮回少年
轮回少年 2021-02-08 18:35

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

相关标签:
3条回答
  • 2021-02-08 18:47

    IMHO, code that acts differently depending from absolute paths is not a good solution. It will be probably better a relative path solution. Use dirname to know the relative directory and os.sep for cross platform compatibility.

    if hasattr(sys, "frozen"):
        main_dir = os.path.dirname(sys.executable)
        full_real_path = os.path.realpath(sys.executable)
    else:
        script_dir = os.path.dirname(__file__)
        main_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
        full_real_path = os.path.realpath(sys.argv[0])
    

    the frozen attribute is python standard.

    Take a look also at Esky : http://pypi.python.org/pypi/esky

    0 讨论(0)
  • 2021-02-08 19:04

    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
    
    0 讨论(0)
  • 2021-02-08 19:05

    Try this:

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

    That is what I use with cx_Freeze to get the directory from where the .exe is really running.

    0 讨论(0)
提交回复
热议问题