ws-bridge / app.py
Ramesh-vani's picture
Update app.py
7a10318
raw
history blame
2.27 kB
import asyncio
import websockets
import subprocess
import os
import signal
async def take_input(websocket,prompt):
await websocket.send(f'input:{prompt}')
user_input = await websocket.recv()
with open('input.txt', 'w') as f:
f.write(user_input )
myinput = open('input.txt')
return user_input
async def run_code(websocket, path):
try:
# Read the code from the WebSocket connection
code = await websocket.recv()
# mod_code = """def make_input(*args):
# if args:
# print(f'>:{args[0]}')
# value = input()
# return value
# else:
# print(f'>:')
# value = input()
# return value"""+'\n'+code.replace("input(", "make_input(")
async with websockets.connect('wss://ramesh-vani-wspython.hf.space') as web:
await web.send(code)
while True:
response = await web.recv()
await send_message(response)
break
async def send_message(message):
await websocket.send(f'data: {message}')
# async def process_input_request(line):
# if line.strip().startswith(b">:"):
# # if b'input:' in line.strip():
# prompt = line.strip()[2:]
# user_input = await take_input(websocket,prompt)
# process.stdin.write(user_input.encode('utf-8') + b'\n')
# await process.stdin.drain()
# async for line in process.stdout:
# await process_input_request(line)
# await send_message(line.strip())
# async for line in process.stderr:
# print(f'error:{line.strip()}')
# await send_message(f'error:{line.strip()}')
# return_code = await process.wait()
# if return_code == 0:
# # await send_message('Code executed successfully')
# pass
# else:
# await send_message(f'error:Execution failed with return code {return_code}')
except Exception as e:
print(f'error: {str(e)}')
await websocket.send(f'error: {str(e)}')
start_server = websockets.serve(run_code, "0.0.0.0", 7860)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()