Skip to content

Instantly share code, notes, and snippets.

@ansrivas
Last active January 25, 2018 19:16
Show Gist options
  • Select an option

  • Save ansrivas/0030cee411b3cc2886ce1e9c2466a937 to your computer and use it in GitHub Desktop.

Select an option

Save ansrivas/0030cee411b3cc2886ce1e9c2466a937 to your computer and use it in GitHub Desktop.
asyncio subprocess with aiohttp
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Initialize module utils."""
import asyncio
from aiohttp import web
class Operations(web.View):
"""."""
async def get(request):
"""."""
loop = self.request.loop
if loop:
print("Using existing loop")
data = await run("loop", loop=loop)
return web.json_response(data)
async def run(*cmd, loop=None):
"""."""
# Create the subprocess, redirect the standard output into a pipe
proc = await asyncio.create_subprocess_shell('/bin/ls -al',
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
loop=loop
)
data = await proc.stdout.read()
line = data.decode('utf-8').rstrip()
await proc.wait()
return line
def create_app():
"""."""
app = web.Application()
res = app.router.add_resource('/add', name='add')
res.add_route('*', Operations)
return app
app = create_app()
# gunicorn async_subprocess:app --access-logfile - --error-logfile - --bind localhost:8080 --worker-class aiohttp.worker.GunicornWebWorker --reload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment