获取Python运行路径

Stardust 2020年08月27日 101次浏览

无论是使用何种方式运行python程序(脚本、命令行、打包的可执行文件),均可使用下列函数返回程序的路径

    import sys, os
    def get_app_path():
        if getattr(sys, 'frozen', False):
            application_path = os.path.dirname(sys.executable)
            running_mode = 'Frozen/executable'
        else:
            try:
                app_full_path = os.path.realpath(__file__)
                application_path = os.path.dirname(app_full_path)
                running_mode = "Non-interactive (e.g. 'python myapp.py')"
            except NameError:
                application_path = os.getcwd()
                running_mode = 'Interactive'
        return application_path, running_mode