我有以下代码:
async def get_balance(exchange, symbol='BTC/USD'):
freeBalance = await exchange.fetchBalance()
symbol1_balance = freeBalance[symbol.split('/')[0]]
symbol2_balance = freeBalance[symbol.split('/')[1]]
return symbol1_balance, symbol2_balance
async def get_balances(exchanges):
futures = [get_balance(exchange) for exchange in exchanges]
balances = await asyncio.gather(*futures)
return balances
exchanges = [exchange1, exchange2, ...]
loop = asyncio.get_event_loop()
results = loop.run_until_complete(get_balances(exchanges))
但我得到了一个错误:
res = loop.run_until_complete(get_balances(exchanges, symbol))
Traceback (most recent call last):
File "C:\Users\Nicolas\Anaconda3\lib\asyncio\base_events.py", line 570, in run_until_complete self.run_forever()
File "C:\Users\Nicolas\Anaconda3\lib\asyncio\base_events.py", line 525, in run_forever raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
main:49: RuntimeWarning: coroutine 'binance.fetch_balance' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback
main:49: RuntimeWarning: coroutine 'bitfinex.fetch_balance' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback
要明确的是: 打印(交换[0].fetchBalance())
<coroutine object binance.fetch_ticker at 0x000001FE6473BA48>
因此,函数get_balance已经是一个协程
我成功地运行了第一个asyncio-example-gather,但没有运行
asyncio.run(main())
File "C:\Users\Nicolas\Anaconda3\lib\asyncio\runners.py", line 34, in run "asyncio.run() cannot be called from a running event loop")
RuntimeError: asyncio.run() cannot be called from a running event loop
但以下工作:
loop = asyncio.get_running_loop()
res = loop.create_task(main())
我非常熟悉异步编程,以前更多地使用多线程。你知道这里怎么了吗
谢谢你们
目前没有回答
相关问题 更多 >
编程相关推荐