summaryrefslogtreecommitdiff
path: root/python/engine.py
diff options
context:
space:
mode:
Diffstat (limited to 'python/engine.py')
-rwxr-xr-xpython/engine.py57
1 files changed, 57 insertions, 0 deletions
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))