如果我错了,请纠正我。 目标是:通过派生到另一个进程来复制一个文件(因此实际的复制不是“锁定”调用它的进程)。在
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)
Popen(cmd, stdout=PIPE, stderr=PIPE)
不会“锁定”父进程。在cmd
如果由于管道缓冲区满而生成足够的输出,则可能会自行暂停。如果要放弃子进程的输出,请使用DEVNULL
而不是PIPE
:如果您想在不阻塞主线程的情况下处理输出,那么可以使用几种方法:
^{pr2}$fcntl
,select
,带iocp的命名管道,threads。后者是一种更便携的方式:其中
bind()
函数:在不阻塞主线程的情况下,不需要外部进程在Python中复制文件:
Python可以在I/O期间释放GIL,因此复制可以同时进行,也可以与主线程并行进行。在
可以将其与使用多个进程的脚本进行比较:
如果您想在程序停止时取消复制,请将
thread_or_process.daemon
属性设置为True
。在在Python中处理复杂异步进程的最简单方法是使用
multiprocessing
库,它是专门为支持这些任务而设计的,它的接口与threading
模块的接口非常相似(事实上,我编写了一些代码,可以通过导入一个或另一个库在多线程和多处理操作之间切换,但这需要对模块的哪些部分进行严格的限制)。在[编辑:删除了关于线程的虚假建议,使我的开场白不那么夸张]
相关问题 更多 >
编程相关推荐