2

Here is my code:

import asyncio, socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('', 1234)) sock.setblocking(False) queue = asyncio.Queue() def sock_reader(): print(sock.recv(1024)) # x = yield from queue def test_sock_reader(): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(b'HELLO', ('127.0.0.1', 1234)) loop = asyncio.get_event_loop() loop.add_reader(sock, sock_reader) loop.call_later(0.5, test_sock_reader) loop.run_forever() loop.close() 

This is the output:

b'HELLO' 

When the line # x = yield from queue is uncommented the program is not printing b'Hello' anymore.

Why is the yield from affecting a command that should already be executed?

1 Answer 1

5

The problem is a combination of syntax and API definition.

First of, refer to the documentation of add_reader, which states that it expects a callback. It is not obvious from the word itself, but by saying callback it means a regular function.

Now, when you uncomment the # x = yield from queue line, your sock_reader function actually becomes a generator/coroutine due to yield from, in which case when called like a regular function (i.e. sock_reader(...)), it returns a generator object, and does not get executed.

Sign up to request clarification or add additional context in comments.

2 Comments

i want sock_reader to wait until the queue has an item. how to do it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.