python subprocess

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结果持续输出到文件里面,来达到显示进度的目的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值