python - “终于”没有在 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()
这可以做到吗?我搜索了,没有找到类似的东西,所以我来到了这里。
解决方案
推荐阅读
- javascript - 如何在反应钩子中创建自定义复选框
- angular - RXJS如何将rest api响应映射到应用程序中的模型?
- python - 使用 Python argparse,如果未指定我的输出文件的名称,我希望使用输入文件的名称
- android - FFmpeg:无法在 Android Q 上使用文件描述符进行搜索
- node.js - docker 化时,Node 在 SSR 中提供空静态文件
- laravel - 验证失败时获取表单身份
- python - 简单问题——这个函数中的 NoSuchElementException 和 WebDriverException 是什么意思?
- javascript - React:作为道具传递的函数无法正常工作
- getstream-io - 查看一个用户是否在关注另一个用户的方法?
- java - 快速java问题,如何使代码静音