python - asyncio:异常时停止协程
问题描述
我正在编写一个必须在捕获异常时自行重启的函数,但我不知道该怎么做。我有这段代码,但它不起作用。:
import asyncio
async def main():
while True:
try:
#REALLY huge amount of code
except Exception as e:
print(f"Exception: {e}")
# Here I want this script to run main() again
return
asyncio.run(main())
解决方案
你的main
函数是一个协程,协程保持状态。重新启动同一个可能不是一个好主意。您需要两个函数, co-routinemain
和一个常规函数 main 来处理创建一个新的 co-routine 并再次运行它。
async def amain():
# Lot of code
def main():
while True:
try:
asyncio.run(amain())
except KeyboardInterrupt:
break
except Exception as e:
log(e)
类似的东西。
推荐阅读
- android - How to Shrink Font in Order to fit Inside Width of View in Android?
- c++ - 内存被删除而不删除调用c ++
- clojure - 在 ClojureScript 命名空间中引用宏
- javascript - 通过重复键和值将 JSON 对象值合并到数组 [javascript]
- python - 从pyspark中第一个rdd的两个基于重复计数的rdds创建对rdd?
- cordova - Cordova 访问 www 下的文件
- python - 在单个列中按多年分组并绘制堆叠的结果
- docker - 在 nginx 反向代理后面的 docker-compose 服务中请求时 axios ECONNREFUSED
- javascript - scrollIntoView() 无法使用普通 JS
- php - 为什么 WooCommerce REST API 似乎不起作用?