From 86737c42e6c7704a44487f2ec936140db2c67d26 Mon Sep 17 00:00:00 2001 From: Timotej Lazar Date: Fri, 21 Aug 2015 15:06:56 +0200 Subject: Add a Python server for running users' code --- python/engine.py | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100755 python/engine.py (limited to 'python/engine.py') diff --git a/python/engine.py b/python/engine.py new file mode 100755 index 0000000..f1b8d36 --- /dev/null +++ b/python/engine.py @@ -0,0 +1,57 @@ +#!/usr/bin/python3 + +# This module submits Python code to the python-tester. + +import http.client +import json + +address, port = 'localhost', 3031 # TODO put this somewhere sane +def request(method, path, body=None): + headers = {'Content-Type': 'application/json;charset=utf-8'} + messages = [] + try: + conn = http.client.HTTPConnection(address, port, timeout=30) + conn.request(method, path, body, headers=headers) + response = conn.getresponse() + if response.status != http.client.OK: + raise Exception('server returned {}'.format(response.status)) + + reply = json.loads(response.read().decode('utf-8')) + return reply + finally: + conn.close() + +# Inputs are given as a list of pairs (expression, stdin). Receives and returns +# a list of answers given as tuples (result, stdout, stderr, exception). +def run(code=None, inputs=None, timeout=1.0): + body = {'code': code, 'inputs': inputs, 'timeout': timeout} + return request('GET', '/run', body=json.dumps(body)) + + +# Basic sanity check. +if __name__ == '__main__': + import time + + code = '''\ +import sys +def foo(x): + y = int(input()) + print(x+y) + sys.stderr.write('bar') + if x+y == 6: + while True: + pass + return x*y +''' + inputs = [ + ('foo(1)', '2\n'), + ('foo(2)', '4\n'), + ('foo(3)', '6\n'), + ] + + start = time.monotonic() + result = run(code=code, inputs=inputs, timeout=1.0) + end = time.monotonic() + for r in result['results']: + print(r) + print('time taken: {:.3f}'.format(end-start)) -- cgit v1.2.1