main.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import sys, shlex, time, subprocess
  4. cmd = "./python.subprocess 0 80000"
  5. args = shlex.split(str(cmd))
  6. print "cmd: %s, args: %s"%(cmd, args)
  7. # the communicate will read all data and wait for sub process to quit.
  8. def use_communicate(args, fout, ferr):
  9. process = subprocess.Popen(args, stdout=fout, stderr=ferr)
  10. (stdout_str, stderr_str) = process.communicate()
  11. return (stdout_str, stderr_str)
  12. # if use subprocess.PIPE, the pipe will full about 50KB data,
  13. # and sub process will blocked, then timeout will kill it.
  14. def use_poll(args, fout, ferr, timeout):
  15. (stdout_str, stderr_str) = (None, None)
  16. process = subprocess.Popen(args, stdout=fout, stderr=ferr)
  17. starttime = time.time()
  18. while True:
  19. process.poll()
  20. if process.returncode is not None:
  21. (stdout_str, stderr_str) = process.communicate()
  22. break
  23. if timeout > 0 and time.time() - starttime >= timeout:
  24. print "timeout, kill process. timeout=%s"%(timeout)
  25. process.kill()
  26. break
  27. time.sleep(1)
  28. process.wait()
  29. return (stdout_str, stderr_str)
  30. # stdout/stderr can be fd, fileobject, subprocess.PIPE, None
  31. fnull = open("/dev/null", "rw")
  32. fout = fnull.fileno()#subprocess.PIPE#fnull#fnull.fileno()
  33. ferr = fnull.fileno()#subprocess.PIPE#fnull#fnull.fileno()
  34. print "fout=%s, ferr=%s"%(fout, ferr)
  35. #(stdout_str, stderr_str) = use_communicate(args, fout, ferr)
  36. (stdout_str, stderr_str) = use_poll(args, fout, ferr, 10)
  37. def print_result(stdout_str, stderr_str):
  38. if stdout_str is None:
  39. stdout_str = ""
  40. if stderr_str is None:
  41. stderr_str = ""
  42. print "terminated, size of stdout=%s, stderr=%s"%(len(stdout_str), len(stderr_str))
  43. while True:
  44. time.sleep(1)
  45. print_result(stdout_str, stderr_str)