[英]python asyncio context manager: combine 2 “contexts” in 1 variable
[英]Long Pause After Asyncio Context Manager
只是想通過一些簡單的例子來asyncio
:
import asyncio
from binance import AsyncClient, BinanceSocketManager
async def main():
# initialise the client
client = await AsyncClient.create()
bsm = BinanceSocketManager(client)
# create listener using async with
# this will exit and close the connection after 5 messages
async with bsm.trade_socket('BTCUSDT') as ts:
for _ in range(5):
res = await ts.recv()
print(f'{_} recv {res}')
print('Hello')
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Output:
0 recv {'e': 'trade', 'E': 1620125896291, 's': 'BTCUSDT', 't': 807604863, 'p': '56336.87000000', 'q': '0.00044900', 'b': 5772457377, 'a': 5772457449, 'T': 1620125896291, 'm': True, 'M': True}
1 recv {'e': 'trade', 'E': 1620125896345, 's': 'BTCUSDT', 't': 807604864, 'p': '56336.88000000', 'q': '0.00099900', 'b': 5772457451, 'a': 5772457310, 'T': 1620125896345, 'm': False, 'M': True}
2 recv {'e': 'trade', 'E': 1620125896556, 's': 'BTCUSDT', 't': 807604865, 'p': '56336.87000000', 'q': '0.01220300', 'b': 5772457377, 'a': 5772457460, 'T': 1620125896555, 'm': True, 'M': True}
3 recv {'e': 'trade', 'E': 1620125896579, 's': 'BTCUSDT', 't': 807604866, 'p': '56336.88000000', 'q': '0.01037100', 'b': 5772457461, 'a': 5772457310, 'T': 1620125896579, 'm': False, 'M': True}
4 recv {'e': 'trade', 'E': 1620125896583, 's': 'BTCUSDT', 't': 807604867, 'p': '56336.88000000', 'q': '0.00091100', 'b': 5772457462, 'a': 5772457310, 'T': 1620125896583, 'm': False, 'M': True}
Hello
每當收到交易事件時,以 0、1、2、3 和 4 開頭的行幾乎立即出現。 但是,在打印Hello
之前會有相當長的停頓(大約 1-5 秒,每次運行都會有所不同)。 暫停的原因是什么?
將“for _ in range(5):”更改為 While True:
然后在你的 print('Hello') "await client.close_connection()" 下面添加這個
對於范圍內的_(5):
將 5 更改為 > 數字。
如果我的理解對您的問題是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.