【问题标题】:Python Copy SpeedPython 复制速度
【发布时间】:2013-10-29 16:41:15
【问题描述】:

我在 Windows 计算机上使用 Python 2.7。 我想知道我的传输比特率是如何复制的。 我有一个源列表和一个目的地列表,并在 for 循环中调用它们。 实际复制由下面的代码完成。

subprocess.call(""" copy  "%s" "%s"  """ % (src_abs_path, dst_abs_path), shell=True)

有没有办法提高我的复制速度?

谢谢 加文

【问题讨论】:

  • 你考虑过使用shutil吗?
  • 我做了简短的。它有能力告诉我传输速度吗?
  • 不,但是shutil 是比您使用的方法更可靠的复制文件的方法...

标签: python copy bitrate


【解决方案1】:

除非copy 命令通过stdout 提供有关比特率的反馈,否则您将需要一个外部python 库来为您执行此操作,或者您通过每秒检查新文件的大小并进行一些数学运算来手动执行此操作。

【讨论】:

  • 所以我尝试通过检查目标文件大小来做到这一点。 code def work(): threading.Timer(0.25,work).start(); x = os.path.getsize(frame.worker.dst_abs_path) wx.CallAfter(frame.getspeed.SetLabel, str(x)) work() code 但是这不会更新文件大小,因为正在复制文件大小.它只给我完成的数字。如果我能找到一种在写入文件时找到大小的方法,我会被排序。
  • 抱歉这里的格式。有人知道如何在此评论部分格式化代码吗?
  • code def work(): threading.Timer(0.25,work).start(); x = os.path.getsize(frame.worker.dst_abs_path) wx.CallAfter(frame.getspeed.SetLabel, str(x)) work() code 与 shutil 一起使用对我有用,谢谢
【解决方案2】:

您可以按照以下方式做一些事情:

#!/usr/bin/python
import sys
import os
import glob

class ProgBar(object):
    def __init__(self, **kwargs):
        self.length=kwargs.get('width', 40)
        self.header=kwargs.get('header', None)
        self.progress=0.0
        self.fmt=kwargs.get('fmt', "[{}] {:6.1%}")

    def start(self, prog=0.0):
        self.progress=prog
        if self.header:
            sys.stdout.write(self.header)

        return self

    def update(self, prog):
        sys.stdout.write('\r')
        if prog>1 or prog<0: raise ValueError('progress outside range')
        self.progress=prog
        block=int(round(self.length*prog))  
        txt=self.fmt.format("#"*block + "-"*(self.length-block), prog)
        self.outlen=len(txt)   
        sys.stdout.write(txt)
        sys.stdout.flush()        

def read_in_chunks(infile, chunk_size=1024):
    while True:
        chunk = infile.read(chunk_size)
        if chunk:
            yield chunk
        else:
            return        

src_path='/tmp' 
dest_path='/tmp/test_dir/1/2/3/4/5'
buf=10                               # artificially small...
os.chdir(src_path)

for file in glob.glob('*.txt'):
    src=os.path.join(src_path,file)
    dst=os.path.join(dest_path,file)
    src_size=os.path.getsize(file)
    with open(src, 'rb') as fin, open(dst, 'w') as fout:
        pb=ProgBar().start()
        print '{}\n=>\n{}'.format(src,dst)
        for i, chunk in enumerate(read_in_chunks(fin, buf), 1):
            fout.write(chunk)
            pb.update(float(i)*buf/src_size)
        print '\ndone'

【讨论】:

  • 这超出了我的能力范围。我去看看。
猜你喜欢
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 2019-12-13
  • 2014-02-06
  • 2018-07-30
  • 1970-01-01
相关资源
最近更新 更多