我是一名新的python程序员,正在尝试编写一个“bot”来为自己在betfair上进行交易。(雄心勃勃!!!!)
我遇到的问题是——我有运行asyncio事件循环的基本知识,但我注意到,如果其中一个协程在其进程中失败(例如API调用失败或mongodb读取失败),那么asyncio事件循环将继续运行,但忽略一个失败的协程
我的问题是,我如何能够自动重新启动一个协程,或者处理一个错误来停止整个asyncio循环,但此时一切运行起来似乎都忘记了一个事实,即有些事情不正确,其中一部分失败了。在我的例子中,在数据库读取未成功后,循环从未返回到“rungetcompetitionids”函数,并且它从未再次返回到函数,即使它处于while true循环中 usergui还不能正常工作,但只能尝试异步IO
谢谢 克莱夫
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()
一个简单的解决方案是使用一个包装函数(或“supervisor”)捕获
Exception
,然后盲目地重试该函数。更优雅的解决方案包括出于诊断目的打印异常和堆栈跟踪,以及查询应用程序状态以查看尝试并继续是否有意义。例如,如果betfair告诉您您的帐户未经授权,那么继续下去就毫无意义。如果这是一个普遍的网络错误,那么立即重试可能是值得的。如果主管注意到它在很短的时间内重新启动了很多次,您也可能希望停止重试例如
这将产生如下输出:
相关问题 更多 >
编程相关推荐