2

我在 rsync 手册中读到 rsync 返回 0 - 35 范围内的退出值。
我尝试使用以下代码捕获 rsync 的输出:

import subprocess, time, os, sys
cmd = ["rsync", "-avuxz", "/etc/passwd" ,"/tmp1/"]

p = subprocess.Popen(cmd,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)

for line in p.stdout:
    print line.rstrip()

使用上面的程序,我从 rsync 捕获了以下输出:

rsync: mkdir "/tmp1" failed: Permission denied (13)
rsync error: error in file IO (code 11) at main.c(587) [Receiver=3.0.9]
rsync: connection unexpectedly closed (9 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at io.c(605) [sender=3.0.9]

我的问题:
- rsync 输出是否仅作为文本(如上)?
- 我如何区分成功(代码 0)和错误?
(假设是否正确:在 Success 的情况下 p.stdout 的长度将为零,而其他任何事情都是失败的?)

4

1 回答 1

1

您可以通过属性访问Popen对象进程的返回码。returncode如果其值为None,则该过程尚未完成;稍后再检查。

例如:

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

# Dumb way to wait for the process to complete
while p.returncode is None:
    os.sleep(1)
if p.returncode:
    print "Error, rsync exited with non-zero status"
else:
    print "Success, rsync exited with zero status"
于 2013-01-23T19:00:19.500 回答