[英]Python for with multiprocess
此脚本从 txt 文件中读取行用作我的外部命令的一部分:
for every line in txt do
os.system(comand)
是否可以使用多进程来提高速度?
i=0
x=[]
for file in os.listdir(carpeta):
if file.endswith('.json'):
x.append(file)
i+=1
print('the total number of files: ' +str(i))
archivo='./temp.txt'
strm=open(archivo,encoding='UTF8')
min=1
for line in strm:
if min > i:
min=1
origen=args.o+"/"+line.rstrip('\n')
destino=re.sub("\/(?:.(?!\/))+$","",args.d+"/"+line.rstrip('\n'))
comando=args.r+" copy \""+origen+"\" \""+destino+"\" --drive-service-account-file \""+carpeta+"\\"+str(min)+".json\" --size-only"
os.system(comando)
min+=1
您可以使用multiprocessing
处理从命令列表中启动 os 进程。
像这样的东西:
import multiprocessing, os, re
from multiprocessing import Process, freeze_support
def getcmdlist():
i=0
x=[]
for file in os.listdir(carpeta):
if file.endswith('.json'):
x.append(file)
i+=1
print('the total number of files: ' +str(i))
archivo='./temp.txt'
strm=open(archivo,encoding='UTF8')
min=1
cmdlist = []
for line in strm:
if min > i:
min=1
origen=args.o+"/"+line.rstrip('\n')
destino=re.sub("\/(?:.(?!\/))+$","",args.d+"/"+line.rstrip('\n'))
comando=args.r+" copy \""+origen+"\" \""+destino+"\" --drive-service-account-file \""+carpeta+"\\"+str(min)+".json\" --size-only"
cmdlist.append(comando)
min+=1
return cmdlist
if __name__ == '__main__':
freeze_support() # needed for Windows
cmdlist = getcmdlist() # all commands
with multiprocessing.Pool(processes=4) as pool:
pool.map(os.system, cmdlist) # pass each command to os process
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.