Skip to content

Commit

Permalink
10 - Asyncio Subprocess & Websockets
Browse files Browse the repository at this point in the history
  • Loading branch information
codingforentrepreneurs committed Aug 25, 2020
1 parent 91a6213 commit 2c59010
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 9 deletions.
8 changes: 4 additions & 4 deletions client.py
Expand Up @@ -7,10 +7,10 @@
async def connect_to_ws(msg):
async with websockets.connect(websocket_endpoint) as ws:
await ws.send(msg)
async for message in ws:
print(message)
await asyncio.sleep(10)
await ws.close()
# async for message in ws:
# print(message)
# await asyncio.sleep(10)
# await ws.close()

if __name__=="__main__":
msg = 'nothing here'
Expand Down
33 changes: 28 additions & 5 deletions index.py
Expand Up @@ -2,21 +2,44 @@
import websockets
import json

async def webhook_handler(websocket, path):
print(websocket, path)

async def call_cli_command(cmd):
'''
python client.py '{"cell_data": "print(\"hello world\")"}'
python client.py '{"cell_data": "print(134243 * 234234)"}'
python client.py '{"cell_data": "!pip freeze"}'
'''
command_args = ['python', '-c', cmd] # ['python', '-c', 'print("hello world")']
if cmd.startswith("!"): # !pip install fastapi
command_args = cmd[1:].split()
proc = await asyncio.create_subprocess_exec(
*command_args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await proc.communicate()
return stdout.decode("utf-8"), stderr.decode("utf-8")


async def websocket_handler(websocket, path):
# print(websocket, path)
async for message in websocket:
data = {}
try:
data = json.loads(message)
except:
pass
print(data.get('data'))
await websocket.send(json.dumps({"this": "awesome"}))
# print(data.get('cell_data'))
cell_data = data.get("cell_data")
if cell_data != None:
stdout, stderr = await call_cli_command(cell_data)
print(stdout, stderr)
# await websocket.send(json.dumps({"this": "awesome"}))
# print(message)
# pass


server = websockets.serve(webhook_handler, 'localhost', 8765)
server = websockets.serve(websocket_handler, 'localhost', 8765)

loop = asyncio.get_event_loop()
loop.run_until_complete(server)
Expand Down
8 changes: 8 additions & 0 deletions reference_examples/subproc.py
@@ -0,0 +1,8 @@
import subprocess

process = subprocess.Popen(['pip', 'freeze'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

stdout, stderr = process.communicate()

print(stdout.decode('utf-8'))
# print(stderr.decode('utf-8'))

0 comments on commit 2c59010

Please sign in to comment.