有时候我们需要帮py脚本打包成exe文件进行分发,那打包之后的exe程序,比如要获取我们当前程序路径下面的某个文件就遇到问题了,如何和我们当前程序的路径呢?

import os
import sys

config_name = 'myapp.cfg'

# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
    application_path = os.path.dirname(sys.executable)
elif __file__:
    application_path = os.path.dirname(__file__)

config_path = os.path.join(application_path, config_name)


参考资料:

https://stackoverflow.com/questions/404744/determining-application-path-in-a-python-exe-generated-by-pyinstaller