Python:使用子进程复制文件

2024-10-03 02:41:08 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我错了,请纠正我。 目标是:通过派生到另一个进程来复制一个文件(因此实际的复制不是“锁定”调用它的进程)。在

cmd = ['cp', '/Users/username/Pictures/2Gb_ImageFile.tif', '/Volume/HugeNetworkDrive/VerySlow/Network/Connection/Destination.tif']

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

copyWithSubprocess(cmd)

Tags: 文件cmd目标进程usernamecpuserssubprocess
2条回答

Popen(cmd, stdout=PIPE, stderr=PIPE)不会“锁定”父进程。在

cmd如果由于管道缓冲区满而生成足够的输出,则可能会自行暂停。如果要放弃子进程的输出,请使用DEVNULL而不是PIPE

import os
from subprocess import Popen, STDOUT

DEVNULL = open(os.devnull, 'wb') #NOTE: it is already defined in Python 3.3+
p = Popen(cmd, stdout=DEVNULL, stderr=STDOUT)
# ...

如果您想在不阻塞主线程的情况下处理输出,那么可以使用几种方法:fcntlselect,带iocp的命名管道,threads。后者是一种更便携的方式:

^{pr2}$

其中bind()函数:

from contextlib import closing
from functools import partial
from threading import Thread

def bind(pipe, callback, chunksize=8192):
    def consume():
        with closing(pipe):
            for chunk in iter(partial(pipe.read, chunksize), b''):
                callback(chunk)
    t = Thread(target=consume)
    t.daemon = True
    t.start()
    return t

在不阻塞主线程的情况下,不需要外部进程在Python中复制文件:

import shutil
from threading import Thread

Thread(target=shutil.copy, args=['source-file', 'destination']).start()

Python可以在I/O期间释放GIL,因此复制可以同时进行,也可以与主线程并行进行。在

可以将其与使用多个进程的脚本进行比较:

import shutil
from multiprocessing import Process

Process(target=shutil.copy, args=['source-file', 'destination']).start()

如果您想在程序停止时取消复制,请将thread_or_process.daemon属性设置为True。在

在Python中处理复杂异步进程的最简单方法是使用multiprocessing库,它是专门为支持这些任务而设计的,它的接口与threading模块的接口非常相似(事实上,我编写了一些代码,可以通过导入一个或另一个库在多线程和多处理操作之间切换,但这需要对模块的哪些部分进行严格的限制)。在

[编辑:删除了关于线程的虚假建议,使我的开场白不那么夸张]

相关问题 更多 >