31
loading...
This website collects cookies to deliver better user experience
ruby_language_server
to python_language_server
, and replacing Ruby code examples by Python examples.#!/usr/bin/env python3
from io import StringIO
import sys
import json
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
self._stderr = sys.stderr
self._stringio = StringIO()
sys.stdout = self._stringio
sys.stderr = self._stringio
return self
def __exit__(self, *args):
output = self._stringio.getvalue()
self.append(output)
sys.stdout = self._stdout
sys.stderr = self._stderr
sessions = {}
for line in sys.stdin:
body = json.loads(line)
session_id = body["session_id"]
code = body["code"]
sessions.setdefault(session_id, {})
error = None
with Capturing() as output:
try:
exec(code, sessions[session_id])
except Exception as e:
error = str(e)
result = {"output": output[0], "error": error}
print(json.dumps(result), flush=True)
for line in sys.stdin
body = json.loads(line)
print(json.dumps(result), flush=True)
flush=True
is important, as communication between processes is normally buffered, so it won't actually be sent until the 4kB buffer is full. This buffering does not happen if you print to the terminal, and normally if you send things to files, you don't care about exact timing of when each line gets there. But when talking to processes, we need to do this.