Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple server that runs a process for each client connection
#!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
import asyncio
import click
async def copy(src, dst):
buf = await
while buf:
await dst.drain()
buf = await
async def handle(cmd, reader, writer):
print('Connection received')
PIPE = asyncio.subprocess.PIPE
process = await asyncio.create_subprocess_exec(*cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
await asyncio.gather(copy(reader, process.stdin),
copy(process.stdout, writer),
copy(process.stderr, writer))
async def start(host, port, cmd):
server = await asyncio.start_server(lambda r, w: handle(cmd, r, w), host, port)
async with server:
await server.serve_forever()
@click.option('-h', '--host', default='', help='address to bind to')
@click.option('-p', '--port', default=31337, help='port to bind to')
@click.argument('cmd', nargs=-1)
def main(host, port, cmd):
"""Server that spawns a process for each new connection""", port, cmd))
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment