-
Notifications
You must be signed in to change notification settings - Fork 19
/
judge.py
57 lines (46 loc) · 1.41 KB
/
judge.py
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
#!/usr/bin/env python3
# Reference
# https://stackoverflow.com/a/31867499
# https://docs.python.org/3/library/threading.html
# https://docs.python.org/3/library/subprocess.html
from subprocess import Popen, PIPE
from threading import Thread
import queue # Python 2
def reader(pipe, q):
try:
for line in iter(pipe.readline, b''):
q.put((pipe, line))
finally:
q.put(None)
def runProcess(command, timeout=10):
process = Popen(command, stdout=PIPE, stderr=PIPE, bufsize=1)
q = queue.Queue()
outTh = Thread(target=reader, args=[process.stdout, q])
errTh = Thread(target=reader, args=[process.stderr, q])
outTh.start()
errTh.start()
outTh.join(timeout=timeout)
errTh.join(timeout=timeout)
outBuf, errBuf = b'', b''
for _ in range(2):
for source, line in iter(q.get, None):
# print ("%s: %s" % (source, line))
if source == process.stdout:
outBuf += line
elif source == process.stderr:
errBuf += line
return outBuf, errBuf
if __name__ == '__main__':
# outBuf, errBuf = runProcess(["python3", "sample.py"])
outBuf, errBuf = runProcess(["gcc", "sample.c"])
print("stdout:")
print(outBuf)
print()
print("stderr:")
print(errBuf)
outBuf, errBuf = runProcess(["./a.out"])
print("stdout:")
print(outBuf)
print()
print("stderr:")
print(errBuf)