Skip to content

Commit 2c59010

Browse files
10 - Asyncio Subprocess & Websockets
1 parent 91a6213 commit 2c59010

File tree

3 files changed

+40
-9
lines changed

3 files changed

+40
-9
lines changed

client.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@
77
async def connect_to_ws(msg):
88
async with websockets.connect(websocket_endpoint) as ws:
99
await ws.send(msg)
10-
async for message in ws:
11-
print(message)
12-
await asyncio.sleep(10)
13-
await ws.close()
10+
# async for message in ws:
11+
# print(message)
12+
# await asyncio.sleep(10)
13+
# await ws.close()
1414

1515
if __name__=="__main__":
1616
msg = 'nothing here'

index.py

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,44 @@
22
import websockets
33
import json
44

5-
async def webhook_handler(websocket, path):
6-
print(websocket, path)
5+
6+
async def call_cli_command(cmd):
7+
'''
8+
python client.py '{"cell_data": "print(\"hello world\")"}'
9+
python client.py '{"cell_data": "print(134243 * 234234)"}'
10+
python client.py '{"cell_data": "!pip freeze"}'
11+
'''
12+
command_args = ['python', '-c', cmd] # ['python', '-c', 'print("hello world")']
13+
if cmd.startswith("!"): # !pip install fastapi
14+
command_args = cmd[1:].split()
15+
proc = await asyncio.create_subprocess_exec(
16+
*command_args,
17+
stdout=asyncio.subprocess.PIPE,
18+
stderr=asyncio.subprocess.PIPE,
19+
)
20+
stdout, stderr = await proc.communicate()
21+
return stdout.decode("utf-8"), stderr.decode("utf-8")
22+
23+
24+
async def websocket_handler(websocket, path):
25+
# print(websocket, path)
726
async for message in websocket:
827
data = {}
928
try:
1029
data = json.loads(message)
1130
except:
1231
pass
13-
print(data.get('data'))
14-
await websocket.send(json.dumps({"this": "awesome"}))
32+
# print(data.get('cell_data'))
33+
cell_data = data.get("cell_data")
34+
if cell_data != None:
35+
stdout, stderr = await call_cli_command(cell_data)
36+
print(stdout, stderr)
37+
# await websocket.send(json.dumps({"this": "awesome"}))
1538
# print(message)
1639
# pass
1740

1841

19-
server = websockets.serve(webhook_handler, 'localhost', 8765)
42+
server = websockets.serve(websocket_handler, 'localhost', 8765)
2043

2144
loop = asyncio.get_event_loop()
2245
loop.run_until_complete(server)

reference_examples/subproc.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import subprocess
2+
3+
process = subprocess.Popen(['pip', 'freeze'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
4+
5+
stdout, stderr = process.communicate()
6+
7+
print(stdout.decode('utf-8'))
8+
# print(stderr.decode('utf-8'))

0 commit comments

Comments
 (0)