Advertisement
Guest User

Untitled

a guest
Sep 30th, 2016
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. import logging
  2. import tempfile
  3. import subprocess
  4.  
  5. class Result(object):
  6.  
  7. def __init__(self, rc, stdout, stderr, cmd):
  8. self.rc = rc
  9. self.stdout = stdout
  10. self.stderr = stderr
  11. self.cmd= cmd
  12.  
  13. def __str__(self):
  14. cutoff = 128
  15. if len(self.stdout) > cutoff:
  16. self.stdout = self.stdout[:cutoff] + '...'
  17. if len(self.stderr) > cutoff:
  18. self.stderr = self.stderr[:cutoff] + '...'
  19.  
  20. return "Result: cmd=%(cmd)s -> " \
  21. "rc=%(rc)s, stdout=%(stdout)s, stderr=%(stderr)s" % {k: repr(self.__dict__[k]) for k in self.__dict__}
  22.  
  23. def run(cmd, shell=True, large_buffer=False):
  24. logging.info("run: '%s' on <localhost>..." % cmd)
  25.  
  26. # subprocess.PIPE is a fixed size (64K) buffer,
  27. # process will be hanging if stdout exceeds this limit.
  28. if large_buffer:
  29. stdout = tempfile.TemporaryFile()
  30. stderr = tempfile.TemporaryFile()
  31. else:
  32. stdout = subprocess.PIPE
  33. stderr = subprocess.PIPE
  34.  
  35. child = subprocess.Popen(
  36. cmd,
  37. shell=shell,
  38. stdout=stdout,
  39. stderr=stderr,
  40. close_fds=False
  41. )
  42.  
  43. child.wait()
  44. rc = child.returncode
  45. if large_buffer:
  46. stdout.seek(0)
  47. stderr.seek(0)
  48. out = stdout.read()
  49. err = stderr.read()
  50. stdout.close()
  51. stderr.close()
  52. else:
  53. out = child.stdout.read()
  54. err = child.stderr.read()
  55.  
  56.  
  57. r = Result(rc, out, err, cmd)
  58. logging.debug(str(r))
  59. if r.rc != 0:
  60. logging.warning("Non-zero return code!!! %s" % r)
  61. logging.debug(r.stdout)
  62. logging.debug(r.stderr)
  63. return r
  64.  
  65. # cmd = "for i in {1..10000}; do echo 'hello world\n'; done"
  66. cmd = "sh -c \"for i in {1..10000}; do echo 'hello world\n'; done\""
  67. # 1. Without using tempfile, the process is hanging.
  68. # r = run(cmd)
  69. # print r
  70.  
  71. # 2. Using tempfile works.
  72. r = run(cmd, large_buffer=True)
  73. print r
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement