Just trying to get my head around asyncio
with some simple examples:
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
The lines starting with 0, 1, 2, 3 and 4 appear pretty much immediately, whenever a trade event is received. However, there is quite a long pause (around 1-5 seconds, it varies upon each run) before Hello
is printed. What is the reason for that pause?
Change "for _ in range(5):" to While True:
Then add this below your print('Hello') "await client.close_connection()"
for _ in range(5):
Change 5 to > number.
If my understanding is correct to your problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.