I'd like to use asyncio to continuously read from a process until I stop it some time later. I've tried tons of things but can't figure out how to do it.
Here's one attempt that just doesn't seem to care about the kill
at all
import io
import asyncio
class Foo():
async def run(self):
proc = await asyncio.create_subprocess_shell('ping www.google.de', stdout=asyncio.subprocess.PIPE)
await asyncio.gather(self.run_proc(proc), self.kill_proc(proc))
async def run_proc(self, proc):
while True:
await asyncio.sleep(0)
line = await proc.stdout.readline()
print(line)
async def kill_proc(self, proc):
await asyncio.sleep(1000)
print("meh")
proc.kill()
f = Foo()
loop = asyncio.get_event_loop()
loop.run_until_complete(f.run())
UPDATE: Here's the working code incorporating the feedback from user4815162342
import io
import asyncio
class Foo():
async def run(self):
proc = await asyncio.create_subprocess_exec('ping', 'www.google.de', stdout=asyncio.subprocess.PIPE)
await asyncio.gather(self.run_proc(proc), self.kill_proc(proc))
async def run_proc(self, proc):
while True:
line = await proc.stdout.readline()
if line == b'':
break
print(line)
async def kill_proc(self, proc):
await asyncio.sleep(1)
print("meh")
proc.kill()
f = Foo()
loop = asyncio.get_event_loop()
loop.run_until_complete(f.run())