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) とエラーを区別するにはどうすればよいですか?
(仮定するのは正しいですか: 成功の場合、 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 に答える