Reputation: 5783
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 printingb'Hello'
anymore.
Why is the yield from
affecting a command that should already be executed?
Upvotes: 2
Views: 592
Reputation: 7418
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.
Upvotes: 5