获取Python运行路径

无论是使用何种方式运行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

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×