您的位置:首页 > 编程语言 > Python开发

python---多线程与多进程

2017-06-14 09:34 393 查看
一. 单进程多线程

1. 使用的模块是Threading。使用join()函数进行阻塞。

1 from pdf2txt import pdfTotxt1, pdfTotxt2
2 import xlrd
3 import os
4 from nltk.corpus import PlaintextCorpusReader
5 from nltk.book import FreqDist
6 import threading
7
8 def handleStock(stock_dir, dir, root_txt_path):
9     for stock in stock_dir:
10         years_dir=os.listdir(dir+stock)
11         for y in years_dir:
12             type_dir=os.listdir(dir+stock+'/'+y)
13             for t in type_dir:
14                 report_dir=os.listdir(dir+stock+'/'+y+'/'+t)
15                 for r in report_dir:
16                     try:
17                         pdfTotxt1(dir+stock+'/'+y+'/'+t+'/'+r, root_txt_path+stock+'_'+y+'_'+t+'_'+r[:-4]+'.txt')
18                     except:
19                         pdfTotxt2(dir+stock+'/'+y+'/'+t+'/'+r, root_txt_path+stock+'_'+y+'_'+t+'_'+r[:-4]+'.txt')
20
21
22 root_pdf_path='/home/luowang/financial_reports_data/attach/'
23 root_txt_path='/usr/lw/result/txt_reports/'
24 Threads=[]
25 if os.path.exists(root_pdf_path):
26     stock_dir=os.listdir(root_pdf_path)
27     length=len(stock_dir)
28     if length>0:
29         for i in range(0,length, 125):
30             if i+125 < length:
31                 dir=stock_dir[i:i+125]
32                 obj=threading.Thread(target=handleStock, args=[dir, root_pdf_path, root_txt_path])
33                 Threads.append(obj)
34                 obj.start()
35             else:
36                 dir=stock_dir[i:length]
37                 obj=threading.Thread(target=handleStock, args=[dir, root_pdf_path, root_txt_path])
38                 Threads.append(obj)
39                 obj.start()


View Code
假定主线程中有一些代码,你希望所有下载程序完成后再执行,这时可以调用Thread对象的join()函数将其阻塞,直到该线程完成。如下面代码所示:

for t in Threads:
t.join()

print 'all file have been handled !!!'


二. 多进程

1. 使用的模块是subprocess,它常用的函数有Popen(), wait(), poll()

1) wait(): 阻塞自己,等待启动的进程终止。它是Popen对象的方法。

>>> t=subprocess.Popen(['start', 'D:\\github.txt'], shell=True)
>>> t.wait()
0


返回值为0,说明程序正常退出了。

2)poll():检查当前进程是否仍在运行,若是返回None, 若正常结束,则返回0,若不正常结束,则返回非0值。它是Popen对象的方法。

>>> t=subprocess.Popen(['start', 'D:\\github.txt'], shell=True)
>>> t.poll()
0


3)Popen(): 启动计算机中的其他程序。

>>> subprocess.Popen(['start', 'D:\\github.txt'], shell=True)
<subprocess.Popen object at 0x02516210>


这里的‘start’表示使用默认程序打开后面的文件。在Windows上,是start程序;在OS X上是open程序; 在Ubuntu Linux上是see程序。

当然,这里也可以用具体的程序的位置代替,比如下面:

>>> import subprocess
>>> subprocess.Popen('C:\\Windoews\\System32\\notepad.exe', 'D:\\github.txt')


未完待续。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: