计算Paramiko中文件传输的剩余时间

时间:2018-05-31 12:06:18

标签: python ssh sftp paramiko

这是我的代码:

def send_file(self,source,destination):
        self.client.open_sftp().put(source,destination,self.upload_status)

def upload_status(self,sent,size):    
    sent_mb=round(sent/1000000,1)
    remaining_mb=round((size-sent)/1000000,1)
    size=round(size/1000000,1)
    sys.stdout.write("Total size:{0} MB|Sent:{1} MB|Remaining:{2} MB".
        format(size,sent_mb,remaining_mb))
    sys.stdout.write('\r')

我得到以下输出:

  

总大小:30.6 |已发送:30.5 MB |剩余:0.1 MB

我的预期输出是:

  

总面积:30.6 |已发送:30.5 MB |剩余:0.1 MB |剩余时间:00:00:01

Paramiko有没有可以给我时间戳的模块?如果没有,我怎么能实现这个目标?

1 个答案:

答案 0 :(得分:0)

  • 记住时间,转移开始时;
  • 在每次更新时,计算转移已经进行的时间;
  • 基于此,计算传输速度;
  • 根据这一点,计算,转移其余部分需要多长时间。
import datetime

# ...

start = datetime.datetime.now()

def upload_status(self, sent, size):
    sent_mb = round(float(sent) / 1000000, 1)
    remaining_mb = round(float(size - sent) / 1000000, 1)
    size_mb = round(size / 1000000, 1)
    time = datetime.datetime.now()
    elapsed = time - start
    if sent > 0:
        remaining_seconds = elapsed.total_seconds() * (float(size - sent) / sent)
    else:
        remaining_seconds = 0
    remaining_hours, remaining_remainder = divmod(remaining_seconds, 3600)
    remaining_minutes, remaining_seconds = divmod(remaining_remainder, 60)
    print(
        ("Total size:{0} MB|Sent:{1} MB|Remaining:{2} MB|" +
         "Time remaining:{3:02}:{4:02}:{5:02}").
        format(
            size_mb, sent_mb, remaining_mb,
            int(remaining_hours), int(remaining_minutes), int(remaining_seconds)))

另请注意,MB计算仅适用于Python 3。在Python 2中,您将删除所有数字。我通过强制转换将其修改为float