|
2 | 2 | import websockets
|
3 | 3 | import json
|
4 | 4 |
|
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) |
7 | 26 | async for message in websocket:
|
8 | 27 | data = {}
|
9 | 28 | try:
|
10 | 29 | data = json.loads(message)
|
11 | 30 | except:
|
12 | 31 | 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"})) |
15 | 38 | # print(message)
|
16 | 39 | # pass
|
17 | 40 |
|
18 | 41 |
|
19 |
| -server = websockets.serve(webhook_handler, 'localhost', 8765) |
| 42 | +server = websockets.serve(websocket_handler, 'localhost', 8765) |
20 | 43 |
|
21 | 44 | loop = asyncio.get_event_loop()
|
22 | 45 | loop.run_until_complete(server)
|
|
0 commit comments