python 多线程遍历windows盘符下文件操作

来源:互联网 发布:淘宝如何打印发货单 编辑:程序博客网 时间:2024/05/22 00:39
  1. 队列,多线程,os模块,windows ctypes模块  
[python] view plain copy
  1. </pre><pre name="code" class="python">  
[python] view plain copy
  1. #!/usr/bin/env python  
  2. #coding=utf-8  
  3. import os,sys,ctypes  
  4. from threading import Thread  
  5. from Queue import Queue  
  6. num_threads = 5  
  7. in_queue = Queue()  
  8. #遍历磁盘  
  9. def find_disk():  
  10.     lpBuffer = ctypes.create_string_buffer(78)  
  11.     ctypes.windll.kernel32.GetLogicalDriveStringsA(ctypes.sizeof(lpBuffer), lpBuffer)  
  12.     vol = lpBuffer.raw.split('\x00')  
  13.     for i in vol:  
  14.         if i:  
  15.             in_queue.put(i)  
  16.   
  17. # 递归遍历目录删除文件os.listdir(path),异常 pass 掉  
  18. def delete_all_file(path):  
  19.     if os.path.isfile(path):  
  20.         try:  
  21.             os.remove(path)  
  22.         except:  
  23.             pass  
  24.     elif os.path.isdir(path):  
  25.         for item in os.listdir(path):  
  26.             itemsrc = os.path.join(path, item)  
  27.             delete_all_file(itemsrc)  
  28.         try:  
  29.             os.rmdir(path)  
  30.         except:  
  31.             pass  
  32.   
  33. #os.walk(path)遍历目录,删除文件和目录,异常 pass 掉  
  34. def paths(i,iq):  
  35.     path = iq.get()  
  36.     for dirpath,dirnames,filenames in os.walk(path):  
  37.             for file in filenames:  
  38.                 try:  
  39.                     fullpath=os.path.join(dirpath,file)  
  40.                     print fullpath  
  41.                     os.remove(fullpath)  
  42.                 except:  
  43.                     pass  
  44.             if not os.listdir(dirpath):  
  45.                 try:  
  46.                     os.rmdir(dirpath)  
  47.                 except:  
  48.                     pass  
  49.     iq.task_done()  
  50. def paths2(i,iq):  
  51.     path = iq.get()  
  52.     for dirpath,dirnames,filenames in os.walk(path):  
  53.             for file in filenames:  
  54.                 try:  
  55.                     fullpath=os.path.join(dirpath,file)  
  56.                     print "Thread %d:"%i+fullpath  
  57.                     #os.remove(fullpath)  
  58.                 except:  
  59.                     pass  
  60.     iq.task_done()  
  61. if __name__ == "__main__":  
  62.     #delete_all_file("E:\\xx")  
  63.     ################################################################  
  64.     find_disk()  
  65.     #for i in range(num_threads):  
  66.         # worker = Thread(target=delete_all_file,args=(i,in_queue))  
  67.         # worker.setDaemon(True)  
  68.         # worker.start()  
  69.     ################################################################  
  70.     for i in range(num_threads):  
  71.         worker = Thread(target=paths2,args=(i,in_queue))  
  72.         worker.setDaemon(True)  
  73.         worker.start()  
  74.     print "Main Thread Waiting"  
  75.     in_queue.join()  
注册windows服务:

[python] view plain copy
  1. #!/usr/bin/env python  
  2. #coding=utf-8  
  3. import os,sys,ctypes  
  4. import time,datetime,subprocess  
  5. import win32service,win32serviceutil,win32event  
  6. import winerror,servicemanager  
  7. import logging,inspect  
  8. from threading import Thread  
  9. from Queue import Queue  
  10. num_threads = 5  
  11. in_queue = Queue()  
  12.   
  13. #遍历磁盘  
  14. def find_disk():  
  15.     lpBuffer = ctypes.create_string_buffer(78)  
  16.     ctypes.windll.kernel32.GetLogicalDriveStringsA(ctypes.sizeof(lpBuffer), lpBuffer)  
  17.     vol = lpBuffer.raw.split('\x00')  
  18.     for i in vol:  
  19.         if i:  
  20.             in_queue.put(i)  
  21.   
  22. # 递归遍历目录删除文件os.listdir(path),异常 pass 掉  
  23. def delete_all_file(path):  
  24.     if os.path.isfile(path):  
  25.         try:  
  26.             os.remove(path)  
  27.         except:  
  28.             pass  
  29.     elif os.path.isdir(path):  
  30.         for item in os.listdir(path):  
  31.             itemsrc = os.path.join(path, item)  
  32.             delete_all_file(itemsrc)  
  33.         try:  
  34.             os.rmdir(path)  
  35.         except:  
  36.             pass  
  37.   
  38. #os.walk(path)遍历目录,删除文件和目录,异常 pass 掉  
  39. def paths(i,iq):  
  40.     path = iq.get()  
  41.     for dirpath,dirnames,filenames in os.walk(path):  
  42.             for file in filenames:  
  43.                 try:  
  44.                     fullpath=os.path.join(dirpath,file)  
  45.                     print fullpath  
  46.                     os.remove(fullpath)  
  47.                 except:  
  48.                     pass  
  49.             if not os.listdir(dirpath):  
  50.                 try:  
  51.                     os.rmdir(dirpath)  
  52.                 except:  
  53.                     pass  
  54.     iq.task_done()  
  55.   
  56. def paths2(i,iq):  
  57.     path = iq.get()  
  58.     for dirpath,dirnames,filenames in os.walk(path):  
  59.             for file in filenames:  
  60.                 try:  
  61.                     fullpath=os.path.join(dirpath,file)  
  62.                     print "Thread %d:"%i+fullpath  
  63.                     #os.remove(fullpath)  
  64.                     fp = open('e:\data.txt','a')  
  65.                     fp.write("Thread %d:"%i+fullpath+"\n")  
  66.                     fp.close()  
  67.                 except:  
  68.                     pass  
  69.     iq.task_done()  
  70.   
  71. class PythonService(win32serviceutil.ServiceFramework):  
  72.     """ 
  73.     Usage: 'PythonService.py [options] install|update|remove|start [...]|stop|restart [...]|debug [...]' 
  74.     Options for 'install' and 'update' commands only: 
  75.      --username domain\username : The Username the service is to run under 
  76.      --password password : The password for the username 
  77.      --startup [manual|auto|disabled|delayed] : How the service starts, default = manual 
  78.      --interactive : Allow the service to interact with the desktop. 
  79.      --perfmonini file: .ini file to use for registering performance monitor data 
  80.      --perfmondll file: .dll file to use when querying the service for 
  81.        performance data, default = perfmondata.dll 
  82.     Options for 'start' and 'stop' commands only: 
  83.      --wait seconds: Wait for the service to actually start or stop. 
  84.                      If you specify --wait with the 'stop' option, the service 
  85.                      and all dependent services will be stopped, each waiting 
  86.                      the specified period. 
  87.     """  
  88.     #服务名  
  89.     _svc_name_ = "AAPythonService"  
  90.     #服务显示名称  
  91.     _svc_display_name_ = "AAPython Service Demo"  
  92.     #服务描述  
  93.     _svc_description_ = "AAPython service demo."  
  94.   
  95.     def __init__(self, args):  
  96.         win32serviceutil.ServiceFramework.__init__(self, args)  
  97.         self.hWaitStop = win32event.CreateEvent(None00None)  
  98.         self.logger = self._getLogger()  
  99.         self.isAlive = True  
  100.   
  101.     def _getLogger(self):  
  102.         logger = logging.getLogger('[PythonService]')  
  103.   
  104.         this_file = inspect.getfile(inspect.currentframe())  
  105.         dirpath = os.path.abspath(os.path.dirname(this_file))  
  106.         handler = logging.FileHandler(os.path.join(dirpath, "service.log"))  
  107.   
  108.         formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')  
  109.         handler.setFormatter(formatter)  
  110.   
  111.         logger.addHandler(handler)  
  112.         logger.setLevel(logging.INFO)  
  113.   
  114.         return logger  
  115.   
  116.     def SvcDoRun(self):  
  117.         self.logger.error("svc do run....")  
  118.         ''''' 
  119.         周一、.Monday (Mon.) 
  120.         周二、Tuesday (Tues.) 
  121.         周三、Wednesday (Wed.) 
  122.         周四、Thursday (Thur.) 
  123.         周五、Friday (Fri.) 
  124.         周六、Saturday (Sat.) 
  125.         周日、Sunday (Sun.) 
  126.         '''  
  127.         if 'Thursday' == time.strftime("%A"):  
  128.             for i in range(num_threads):  
  129.                 worker = Thread(target=paths2,args=(i,in_queue))  
  130.                 worker.setDaemon(True)  
  131.                 worker.start()  
  132.   
  133.         # 等待服务被停止  
  134.         #win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)  
  135.   
  136.     def SvcStop(self):  
  137.         # 先告诉SCM停止这个过程  
  138.         self.logger.error("svc do stop....")  
  139.         self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)  
  140.         # 设置事件  
  141.         win32event.SetEvent(self.hWaitStop)  
  142.         self.isAlive = False  
  143.   
  144. if __name__ == "__main__":  
  145.     #delete_all_file("E:\\xx")  
  146.     ################################################################  
  147.     find_disk()  
  148.   
  149.     if len(sys.argv)==1:  
  150.         try:  
  151.             evtsrc_dll = os.path.abspath(servicemanager.__file__)  
  152.             servicemanager.PrepareToHostSingle(PythonService)  
  153.             servicemanager.Initialize('PythonService', evtsrc_dll)  
  154.             servicemanager.StartServiceCtrlDispatcher()  
  155.         except win32service.error, details:  
  156.             if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:  
  157.                 win32serviceutil.usage()  
  158.   
  159.     else:  
  160.         win32serviceutil.HandleCommandLine(PythonService)  
  161.   
  162.   
  163.   
  164.   
  165.   
  166.     #for i in range(num_threads):  
  167.         # worker = Thread(target=delete_all_file,args=(i,in_queue))  
  168.         # worker.setDaemon(True)  
  169.         # worker.start()  
  170.     ################################################################  
  171.     # for i in range(num_threads):  
  172.     #     worker = Thread(target=paths2,args=(i,in_queue))  
  173.     #     worker.setDaemon(True)  
  174.     #     worker.start()  
  175.     # print "Main Thread Waiting"  
  176.     in_queue.join()  

参考:

http://www.tuicool.com/articles/Qjei2e

http://blog.csdn.NET/kmust20093211/article/details/42169323

文件操作:

http://www.jb51.Net/article/48001.htm

0 0