How to Get the Path of the executing frozen script

微笑、不失礼 提交于 2019-12-03 12:33:56

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!