Last active
January 25, 2018 19:16
-
-
Save ansrivas/0030cee411b3cc2886ce1e9c2466a937 to your computer and use it in GitHub Desktop.
asyncio subprocess with aiohttp
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/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