Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import logging
- import tempfile
- import subprocess
- class Result(object):
- def __init__(self, rc, stdout, stderr, cmd):
- self.rc = rc
- self.stdout = stdout
- self.stderr = stderr
- self.cmd= cmd
- def __str__(self):
- cutoff = 128
- if len(self.stdout) > cutoff:
- self.stdout = self.stdout[:cutoff] + '...'
- if len(self.stderr) > cutoff:
- self.stderr = self.stderr[:cutoff] + '...'
- return "Result: cmd=%(cmd)s -> " \
- "rc=%(rc)s, stdout=%(stdout)s, stderr=%(stderr)s" % {k: repr(self.__dict__[k]) for k in self.__dict__}
- def run(cmd, shell=True, large_buffer=False):
- logging.info("run: '%s' on <localhost>..." % cmd)
- # subprocess.PIPE is a fixed size (64K) buffer,
- # process will be hanging if stdout exceeds this limit.
- if large_buffer:
- stdout = tempfile.TemporaryFile()
- stderr = tempfile.TemporaryFile()
- else:
- stdout = subprocess.PIPE
- stderr = subprocess.PIPE
- child = subprocess.Popen(
- cmd,
- shell=shell,
- stdout=stdout,
- stderr=stderr,
- close_fds=False
- )
- child.wait()
- rc = child.returncode
- if large_buffer:
- stdout.seek(0)
- stderr.seek(0)
- out = stdout.read()
- err = stderr.read()
- stdout.close()
- stderr.close()
- else:
- out = child.stdout.read()
- err = child.stderr.read()
- r = Result(rc, out, err, cmd)
- logging.debug(str(r))
- if r.rc != 0:
- logging.warning("Non-zero return code!!! %s" % r)
- logging.debug(r.stdout)
- logging.debug(r.stderr)
- return r
- # cmd = "for i in {1..10000}; do echo 'hello world\n'; done"
- cmd = "sh -c \"for i in {1..10000}; do echo 'hello world\n'; done\""
- # 1. Without using tempfile, the process is hanging.
- # r = run(cmd)
- # print r
- # 2. Using tempfile works.
- r = run(cmd, large_buffer=True)
- print r
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement