fork(1) download
  1. import time
  2. import threading
  3. import subprocess
  4.  
  5. class Command(object):
  6. def __init__(self, cmd, inp_path, out_path):
  7. self.cmd = cmd.split(' ')
  8. self.process = None
  9. self.inp_path = inp_path
  10. self.out_path = out_path
  11.  
  12. def run(self, timeout):
  13. def target():
  14. f = open(self.inp_path, 'r')
  15.  
  16. out = open(self.out_path,'w')
  17.  
  18. self.process = subprocess.Popen(self.cmd,
  19. bufsize = 4096,
  20. shell = False,
  21. stdin = f,
  22. stdout = out)
  23. self.process.communicate()
  24. out.flush()
  25. return_code = 0
  26. thread = threading.Thread(target = target)
  27. thread.start()
  28. thread.join(timeout)
  29. if thread.isAlive():
  30. return_code = 123456
  31. try:
  32. self.process.terminate()
  33. thread.join()
  34. except AttributeError:
  35. pass
  36. else:
  37. return_code = self.process.returncode
  38. return return_code
  39.  
  40. c = Command('./a.out', '/tmp/in.txt', '/tmp/out.txt')
  41. return_code = c.run(timeout = 2) #timelimit.
  42.  
  43. if return_code == 123456:
  44. print 'TLE' #Time Limit Exceeded
  45. elif return_code == 0:
  46. print 'Program ran successfully' #Either WA/AC
  47. else:
  48. print 'RTE' #Run Time Error
Runtime error #stdin #stdout #stderr 0s 92480KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "prog.py", line 14, in target
IOError: [Errno 2] No such file or directory: '/tmp/in.txt'

Traceback (most recent call last):
  File "prog.py", line 43, in <module>
  File "prog.py", line 39, in run
AttributeError: 'NoneType' object has no attribute 'returncode'