rsync退出值

2 投票
1 回答
2169 浏览
提问于 2025-04-17 13:26

我在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)和错误呢?
(我可以假设:如果成功,p.stdout的长度为零,其他情况都是失败吗?)

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"

撰写回答