Created
August 17, 2016 16:37
-
-
Save pjvandehaar/725f4bba60eea52c252c3d65dc81c8a4 to your computer and use it in GitHub Desktop.
This file contains 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/env python3 | |
import asyncio | |
import sys | |
class StdOutProtocol(asyncio.SubprocessProtocol): | |
def __init__(self, exit_future): | |
self.exit_future = exit_future | |
self.output = bytearray() | |
def pipe_data_received(self, fd, data): | |
self.output.extend(data) | |
def process_exited(self): | |
self.exit_future.set_result(True) | |
@asyncio.coroutine | |
def run_sh(loop, sh_command): | |
exit_future = asyncio.Future(loop=loop) | |
# Create the subprocess controlled by the protocol StdOutProtocol, redirect the standard output into a pipe | |
transport, protocol = yield from loop.subprocess_exec(lambda: StdOutProtocol(exit_future), | |
'sh', '-c' , sh_command, | |
stdin=None, stderr=None) | |
# Wait for the subprocess exit using the process_exited() method of the protocol | |
yield from exit_future | |
# Close the stdout pipe | |
transport.close() | |
# Read the output which was collected by the pipe_data_received() method of the protocol | |
data = bytes(protocol.output) | |
return data.decode('ascii').rstrip() | |
loop = asyncio.get_event_loop() | |
result = loop.run_until_complete(run_sh(loop, 'sleep 2 && date +%Y-%m-%d')) | |
print("result:", result) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment