Skip to content

Instantly share code, notes, and snippets.

@slyshykO
Created August 28, 2024 16:32
Show Gist options
  • Save slyshykO/871bdc35df7ccb37e703a2709cfa2283 to your computer and use it in GitHub Desktop.
Save slyshykO/871bdc35df7ccb37e703a2709cfa2283 to your computer and use it in GitHub Desktop.
async stdout & stderr for process in python
#!/usr/bin/python3
# encoding: utf-8
import platform
import asyncio
@asyncio.coroutine
def _read_stream(stream, cb):
while True:
line = yield from stream.readline()
if line:
cb(line)
else:
break
@asyncio.coroutine
def _stream_subprocess(cmd, stdout_cb, stderr_cb):
process = yield from asyncio.create_subprocess_exec(*cmd,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
yield from asyncio.wait([
_read_stream(process.stdout, stdout_cb),
_read_stream(process.stderr, stderr_cb)
])
yield from process.wait()
return process.returncode
def execute(cmd, stdout_cb, stderr_cb):
loop = None
if platform.system() == "Windows":
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
else:
loop = asyncio.SelectorEventLoop()
asyncio.set_event_loop(loop)
rc = loop.run_until_complete(_stream_subprocess(cmd,stdout_cb,stderr_cb))
loop.close()
return rc
if __name__ == '__main__':
if platform.system() == "Windows":
cmd = ['ping', '192.168.1.210', '-n', '10']
else:
cmd = ['ping', '192.168.1.210', '-c', '10']
print(execute(
cmd,
lambda x: print("STDOUT: %s" % x),
lambda x: print("STDERR: %s" % x),
))
print('--------------------------------------------\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment