【发布时间】:2020-12-29 19:54:09
【问题描述】:
我是一名新的 Python 程序员,正在尝试编写一个“机器人”来为自己在必发进行交易。 (雄心勃勃!!!!)
我出现的问题是——我有一个 asyncio 事件循环运行的基础知识,但我注意到如果其中一个协程在其过程中失败(例如 API 调用失败或 mongodb 读取),那么 asyncio事件循环只是继续运行,但忽略了一个失败的协程
我的问题是如何自动重新启动一个协程或处理错误以停止完整的 asyncio 循环,但目前一切运行似乎都没有注意到某些事情不正确并且其中一部分失败的事实。在我的情况下,在数据库读取不成功后,循环从未返回到“rungetcompetitionids”函数,并且即使它处于一个真正的循环中,它也从未再次返回到该函数 usergui 还没有功能,但只能在那里尝试 asyncio
谢谢 克莱夫
import sys
import datetime
from login import sessiontoken as gst
from mongoenginesetups.setupmongo import global_init as initdatabase
from asyncgetcompetitionids import competition_id_pass as gci
from asyncgetcompetitionids import create_comp_id_table_list as ccid
import asyncio
import PySimpleGUI as sg
sg.change_look_and_feel('DarkAmber')
layout = [
[sg.Text('Password'), sg.InputText(password_char='*', key='password')],
[sg.Text('', key='status')],
[sg.Button('Submit'), sg.Button('Cancel')]
]
window = sg.Window('Betfair', layout)
def initialisethedatabase():
initdatabase('xxxx', 'xxxx', xxxx, 'themongo1', True)
async def runsessiontoken():
nextlogontime = datetime.datetime.now()
while True:
returned_login_time = gst(nextlogontime)
nextlogontime = returned_login_time
await asyncio.sleep(15)
async def rungetcompetitionids(compid_from_compid_table_list):
nextcompidtime = datetime.datetime.now()
while True:
returned_time , returned_list = gci(nextcompidtime, compid_from_compid_table_list)
nextcompidtime = returned_time
compid_from_compid_table_list = returned_list
await asyncio.sleep(10)
async def userinterface():
while True:
event, value = window.read(timeout=1)
if event in (None, 'Cancel'):
sys.exit()
if event != "__TIMEOUT__":
print(f"{event} {value}")
await asyncio.sleep(0.0001)
async def wait_list():
await asyncio.wait([runsessiontoken(),
rungetcompetitionids(compid_from_compid_table_list),
userinterface()
])
initialisethedatabase()
compid_from_compid_table_list = ccid()
print(compid_from_compid_table_list)
nextcompidtime = datetime.datetime.now()
print(nextcompidtime)
loop = asyncio.get_event_loop()
loop.run_until_complete(wait_list())
loop.close()
【问题讨论】:
-
使用
asyncio.gather(x, y, z)代替asyncio.wait([x, y, z])。如果协程引发,gather也会引发,从而停止循环。使用asyncio.wait()是错误的,除非您检查返回值或有专门的用例,例如return_when=FIRST_COMPLETED。 -
感谢您,它已被纳入我的解决方案中
标签: python python-asyncio coroutine