运行 shutil.make_archive 在多线程文件中随机丢失
Running shutil.make_archive in multithreaded files randomly missing
编写一个脚本,压缩命令参数指定路径中的每个子目录,并删除原始子目录。
对于单线程情况,它工作正常,但是当我 运行 它在多线程中使用 concurrent.futures.ThreadPoolExecutor() (auto_zip()) (auto_zip_multi_thread()) 一些文件可能不包含在压缩的 zip 中。
每次丢失文件的百分比都不同,运行在同一个目录中多次使用它每次都会给你不同的结果。
该过程可以毫无瑕疵地完成。
我不能像这样重现它,但是我能做些什么来修复它呢?一种
我不知道其中的区别,因为解压缩 zip 并删除原始 zip 的类似脚本可以正常工作。
import shutil
from concurrent import futures
def task(paths):
while True:
try:
path = next(paths)
shutil.make_archive(path, 'zip', path)
except StopIteration:
break
with futures.ThreadPoolExecutor(max_workers=4) as ex:
for i in range(4):
ex.submit(task, paths)
make_archive()
不是线程安全的。
相反,它通过调用命令 subprocess.run()
within 来解决。 cd
zip
import subprocess
def task(paths):
while True:
try:
path = next(paths)
cmd = f"zip -r {path}.zip {path}"
subprocess.run(cmd)
except StopIteration:
break
编写一个脚本,压缩命令参数指定路径中的每个子目录,并删除原始子目录。 对于单线程情况,它工作正常,但是当我 运行 它在多线程中使用 concurrent.futures.ThreadPoolExecutor() (auto_zip()) (auto_zip_multi_thread()) 一些文件可能不包含在压缩的 zip 中。 每次丢失文件的百分比都不同,运行在同一个目录中多次使用它每次都会给你不同的结果。 该过程可以毫无瑕疵地完成。 我不能像这样重现它,但是我能做些什么来修复它呢?一种 我不知道其中的区别,因为解压缩 zip 并删除原始 zip 的类似脚本可以正常工作。
import shutil
from concurrent import futures
def task(paths):
while True:
try:
path = next(paths)
shutil.make_archive(path, 'zip', path)
except StopIteration:
break
with futures.ThreadPoolExecutor(max_workers=4) as ex:
for i in range(4):
ex.submit(task, paths)
make_archive()
不是线程安全的。
相反,它通过调用命令 subprocess.run()
within 来解决。 cd
zip
import subprocess
def task(paths):
while True:
try:
path = next(paths)
cmd = f"zip -r {path}.zip {path}"
subprocess.run(cmd)
except StopIteration:
break