Advertisement
Guest User

Untitled

a guest
Feb 7th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. from threading import Thread
  3. import json, os, signal, subprocess, time
  4.  
  5.  
  6. class ThreadPopen(Thread):
  7. def __init__(self, cmd, timeout = 60):
  8. self.key = str(cmd[0])
  9. Thread.__init__(self, name=self.key)
  10.  
  11. self.cmd = cmd
  12. self.timeout = timeout
  13. self.t0 = None
  14. self.result = None
  15.  
  16. def __getitem__(self, key):
  17. try:
  18. return self.__dict__[key]
  19. except KeyError as e:
  20. raise AttributeError()
  21.  
  22. def run_popen(self):
  23. process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  24. while process.poll() is None:
  25. time.sleep(0.1)
  26. if time.time() - self.t0 > self.timeout:
  27. os.kill(process.pid, signal.SIGKILL)
  28. os.waitpid(-1, os.WNOHANG)
  29. self.result = (None, None)
  30. break
  31.  
  32. if process.poll() is not None:
  33. _stdout, _stderr = process.communicate()
  34. self.result = (_stdout, _stderr)
  35.  
  36. def run(self):
  37. self.t0 = time.time()
  38. try:
  39. self.run_popen()
  40. except:
  41. print "Failed to call self.run_popen() for " + self.cmd
  42.  
  43.  
  44. def main():
  45. cmd_ls = []
  46. proc_ls = []
  47. res_ls = []
  48.  
  49. for cmd in cmd_ls:
  50. try:
  51. proc = ThreadPopen(cmd)
  52. proc_ls.append(proc)
  53. proc_ls[-1].start()
  54. except:
  55. print "Failed to init or start ThreadPopen() for " + cmd
  56.  
  57. for proc in proc_ls:
  58. proc.join()
  59.  
  60. for proc in proc_ls:
  61. res_ls.append(proc.result)
  62.  
  63. print res_ls
  64.  
  65.  
  66. if __name__ == "__main__":
  67. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement