Skip to main content
 首页 » 编程设计

python之rsync 退出值

2025年05月04日9findumars

我在 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 的长度将为零并且 还有什么是失败的?)

请您参考如下方法:

您可以通过returncode 访问Popen 对象进程的返回码。属性。如果它的值为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"