我正在使用 rsync 备份 Raspberry Pi。rsync 命令在 python 脚本中运行:
import os
os.system('sudo rsync -avzh --stats /etc /home /usr /mnt/BigMac/BigMac/PiBackups/PiZero')
脚本运行良好,这是输出的示例:
Number of files: 599,381 (reg: 468,108, dir: 83,703, link: 45,492, dev: 2,031, special: 47)
Number of created files: 18 (reg: 18)
Number of deleted files: 0
Number of regular files transferred: 39
Total file size: 23.84G bytes
Total transferred file size: 58.12M bytes
Literal data: 58.12M bytes
Matched data: 0 bytes
File list size: 524.10K
File list generation time: 0.001 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 18.37M
Total bytes received: 87.33K
sent 18.37M bytes received 87.33K bytes 2.84M bytes/sec
total size is 23.84G speedup is 1,291.70
我想从此输出中提取两个数值。具体来说,我想从中提取数值 文件总大小:23.84G 字节和 发送的总字节数:18.37M
这两个值最终将在脚本的后面发布到我的 MQTT 代理。
我将不胜感激任何帮助。
答案1
类似这样的事情应该对你有用:
import re
import subprocess
# Exec the command and get the output
output = subprocess.getoutput('sudo rsync -avzh --stats /etc /home /usr /mnt/BigMac/BigMac/PiBackups/PiZero')
# Should do some error handling here, if needed. output can be stderr
# Match total file size, capture it into group 1
# Line from start to end with non-greedy anything before "bytes" captured
# It could be more accurate like (\d+(?:\.\d+)?[A-Z]) but I don't know exact possible formats
total_size = re.search(r'^Total file size: (.*?) bytes$', output, re.MULTILINE).group(1)
# Match total bytes, capture it into group 1, similarly as above
total_bytes = re.search(r'^Total bytes sent: (.*?)$', output, re.MULTILINE).group(1)