问题是,FG
将输出直接重定向到程序的标准输出。见https://github.com/tomerfiliba/plumbum/blob/master/plumbum/commands.py#L611
当输出以这种方式重定向时,它不会通过铅的机器,所以你不会在异常对象中得到它。如果您愿意阻止直到slow_cmd
完成,更好的解决方案是自己从标准输出中读取。这是一个草图:
lines = []
p = slow_cmd.popen()
while p.poll() is None:
line = p.stdout.readline()
lines.append(line)
print line
if p.returncode != 0:
print "see log file..."
一个更优雅的解决方案是编写自己的 ExecutionModifier(如FG
)来复制输出流。让我们称之为TEE
(在http://en.wikipedia.org/wiki/Tee_(command)之后)......我没有测试过它,但它应该可以解决问题(减去select
stdout/err ):
class TEE(ExecutionModifier):
def __init__(self, retcode = 0, dupstream = sys.stdout):
ExecutionModifier.__init__(self, retcode)
self.dupstream = dupstream
def __rand__(self, cmd):
p = cmd.popen()
stdout = []
stderr = []
while p.poll():
# note: you should probably select() on the two pipes, or make the pipes nonblocking,
# otherwise readline would block
so = p.stdout.readline()
se = p.stderr.readline()
if so:
stdout.append(so)
dupstream.write(so)
if se:
stderr.append(se)
dupstream.write(se)
stdout = "".join(stdout)
stderr = "".join(stderr)
if p.returncode != self.retcode:
raise ProcessExecutionError(p.argv, p.returncode, stdout, stderr)
return stdout, stderr
try:
stdout, stderr = slow_cmd & TEE()
except ProcessExecutionError as e:
pass # find the log file, etc.