相关疑难解决方法(0)

多处理与线程Python

我试图了解多处理优于线程的优势.我知道多处理可以解决Global Interpreter Lock问题,但是还有什么其他优点,并且线程不能做同样的事情?

python multithreading multiprocessing

739
推荐指数
10
解决办法
32万
查看次数

Python:如何快速复制文件

它需要更长的时间至少3次与复制文件shutil.copyfile()与使用Windows资源管理器或Mac的Finder经常右击复制>右键单击粘贴.shutil.copyfile()在Python中有没有更快的替代方案?如何加快文件复制过程?(文件目标位于网络驱动器上......如果它有任何区别......).

稍后编辑:

以下是我最终得到的结果:

def copyWithSubprocess(cmd):        
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

win=mac=False
if sys.platform.startswith("darwin"):mac=True
elif sys.platform.startswith("win"):win=True

cmd=None
if mac: cmd=['cp', source, dest]
elif win: cmd=['xcopy', source, dest, '/K/O/X']

if cmd: copyWithSubprocess(cmd)
Run Code Online (Sandbox Code Playgroud)

python shutil file-copying

12
推荐指数
2
解决办法
2万
查看次数

从包含数百万个文件的目录(bash/python/perl)中通过精确匹配有效地查找数千个文件

我在 Linux 上,我试图从包含数百万个文件的目录 (SOURCE_DIR) 中查找数千个文件。我有一个需要查找的文件名列表,存储在单个文本文件 (FILE_LIST) 中。该文件的每一行都包含一个与 SOURCE_DIR 中的文件相对应的名称,并且该文件中有数千行。

## FILE_LIST contain single word file names, each per line
#Name0001
#Name0002
#..
#Name9999
Run Code Online (Sandbox Code Playgroud)

我想将文件复制到另一个目录 (DESTINATION_DIR)。我写了下面的循环,里面有循环,一一查找。

#!/bin/bash
FILE_LIST='file.list'
## FILE_LIST contain single word file names, each per line
#Name0001
#Name0002
#..
#Name9999

SOURCE_DIR='/path/to/source/files' # Contain millions of files in sub-directories
DESTINATION_DIR='/path/to/destination/files' # Files will be copied to here


while read FILE_NAME
do
    echo $FILE_NAME
    for FILE_NAME_WITH_PATH in `find SOURCE_DIR -maxdepth 3 -name "$FILE_NAME*" -type f -exec readlink -f {} \;`; 
    do …
Run Code Online (Sandbox Code Playgroud)

python bash perl find

4
推荐指数
1
解决办法
330
查看次数

多线程文件复制比多核CPU上的单个线程慢得多

我试图用Python编写一个多线程程序来加速(低于1000).csv文件的复制.多线程代码比顺序方法运行得更慢.我用时间计算代码profile.py.我相信我一定做错了什么,但我不确定是什么.

环境:

  • 四核CPU.
  • 2个硬盘,一个包含源文件.另一个是目的地.
  • 1000个csv文件,大小从几KB到10 MB不等.

该方法:

我将所有文件路径放在一个队列中,并创建4-8个工作线程从队列中拉出文件路径并复制指定的文件.在任何情况下,多线程代码都不会更快:

  • 顺序复制需要150-160秒
  • 线程副本需要230秒

我假设这是一个I/O绑定任务,因此多线程应该有助于操作速度.

代码:

    import Queue
    import threading
    import cStringIO 
    import os
    import shutil
    import timeit  # time the code exec with gc disable
    import glob    # file wildcards list, glob.glob('*.py')
    import profile # 

    fileQueue = Queue.Queue() # global
    srcPath  = 'C:\\temp'
    destPath = 'D:\\temp'
    tcnt = 0
    ttotal = 0

    def CopyWorker():
        while True:
            fileName = fileQueue.get()
            fileQueue.task_done()
            shutil.copy(fileName, destPath)
            #tcnt += 1
            print 'copied: ', tcnt, ' of …
Run Code Online (Sandbox Code Playgroud)

python queue multithreading copy file

3
推荐指数
1
解决办法
4583
查看次数