Created
August 28, 2024 16:32
-
-
Save slyshykO/871bdc35df7ccb37e703a2709cfa2283 to your computer and use it in GitHub Desktop.
async stdout & stderr for process in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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