首页 > 解决方案 > “终于”没有在 pycharm 停止按钮上执行;还有另一种方法可以很好地清理吗?

问题描述

我正在使用 PyCharm,我有一个问题。在下面的代码中,我创建了一个将连接到服务器并在 game_loop 方法中运行客户端的类,以及一个将我与该服务器断开连接的方法。完成后,我按下 PyCharm 界面上的按钮停止程序,但 finally 中的代码没有运行,我仍然连接到服务器 2-3 秒,直到它崩溃。我希望能够以与我现在退出相同的方式退出,通过终止进程,然后以某种方式运行函数 terminate_all()

class Game(object):
    def game_loop(self):
        # Connect to server

        while True:
            try:
                # Run the client
                pass
            finally:
                self.terminate_all()

    def terminate_all(self):
        # Disconnect from the server
        pass


def main():
    try:
        game_loop()
    finally:
        print('EXIT')


if __name__ == '__main__':
    main()

这可以做到吗?我搜索了,没有找到类似的东西,所以我来到了这里。

标签: pythonexecutetermination

解决方案


推荐阅读