summaryrefslogtreecommitdiff
path: root/python/engine.py
blob: 4a124434e116e3259875e2ee628daec998dfc79c (plain)
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
#!/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(path, args=None):
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    body = json.dumps(args)
    try:
        conn = http.client.HTTPConnection(address, port, timeout=30)
        conn.request('GET', path, body=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):
    return request('/run', {'code': code, 'inputs': inputs, 'timeout': timeout})


# 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))