[英]Running multiple programs together in the shell script in infinite while loop
[英]Running multiple programs from the for loop
该程序一一打印出每个文本文件的行数:
files = glob.glob('*.txt') # 5 files
for f in files:
with open(f,'r') as fi:
lines = fi.read().splitlines()
print len(lines)
如何编写代码,使其同时运行5个程序并分别在每个程序中打印行数?
这是您的程序的多线程版本:
import threading
# called by each thread
def do_task(f) :
with open(f,'r') as fi:
lines = fi.read().splitlines()
print len(lines)
threads = []
files = glob.glob('*.txt') # 5 files
for f in files:
t = threading.Thread(target=do_task, args = (f))
threads.append(t)
t.start()
for t in threads :
t.join()
有趣的是,这里有多进程版本:
from multiprocessing import Process
# called by each thread
def do_task(f, l) :
with open(f,'r') as fi:
lines = fi.read().splitlines()
l.append(lines)
lengths = []
processes = []
files = glob.glob('*.txt') # 5 files
for f in files:
p = Process(target=do_task, args = (f,lengths,))
processes.append(p)
p.start()
for p in processes :
p.join()
for l in lengths:
print l
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.