File size: 2,271 Bytes
d2db5a7
 
7a10318
 
 
d2db5a7
7a10318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26bfbb3
7a10318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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()