import subprocess
import sys
import time
import random
import os
import re
if __name__ == '__main__':
# 构建 rsync 命令
cmdLine = [
'sshpass', '-p', 'password',
'rsync', '--progress',
'--rsh=ssh -o StrictHostKeyChecking=no',
'/opt/software/apache-doris-dependencies-1.2.4.1-bin-x86_64.tar.xz',
'account@ip:/opt/software/'
]
# 生成临时文件
tmpFile = f"./tmp/{random.randint(10000, 99999)}.tmp"
# 创建临时文件所在目录
os.makedirs(os.path.dirname(tmpFile), exist_ok=True)
try:
# 以写入模式打开临时文件
with open(tmpFile, 'w') as fpWrite:
# 启动子进程执行 rsync 命令,将标准输出重定向到临时文件,捕获标准错误
process = subprocess.Popen(cmdLine, stdout=fpWrite, stderr=subprocess.PIPE)
while True:
# 以读取模式打开临时文件
with open(tmpFile, 'r') as fpRead:
# 读取临时文件中的所有行
lines = fpRead.readlines()
for line in lines:
progress_pattern = re.compile(r'(\d+)%')
match = progress_pattern.search(line.strip())
if match:
progress = match.group(1)
print(f"Progress: {progress}%")
# 打印每一行内容
# print(line.strip())
# 检查进程是否结束
if process.poll() is not None:
break
# 清空临时文件内容,以便记录下一次的进度信息
with open(tmpFile, 'w') as fpWrite:
fpWrite.truncate()
# 适当休眠,避免频繁读取文件
time.sleep(3)
# 读取标准错误信息
error = process.stderr.read().decode('utf-8')
if error:
print(f'error info: {error}')
except Exception as e:
print(f"执行过程中出现异常: {e}")
finally:
print('')
# 删除临时文件
if os.path.exists(tmpFile):
os.remove(tmpFile)
print('finished')
将rsync结果持续输出到文件里面,来达到显示进度的目的