多线程写文件实例

Python多线程写文件实例          博客分类:

由于最近一段时间,学了一门脚本语言-Python,原因是一、公司需要;二、只掌握Java感觉还是不够。 由于需要用python分析日志,但是日志实际还没有,格式已经定了,所以我先用python写了个多线程写文件的工具,比较简单,作为一个学习总结吧,同时还遇到了一个问题,顺便将问题和解决方法也总结一下。 需求:两个线程同时向一个文件中写固定格式的文件 实际代码:
Java代码 复制代码 收藏代码
  1. # -*- coding: utf-8 -*-  
  2.   
  3. import threading  
  4.   
  5. '''  
  6. 多线程生成日志工具  
  7. '''  
  8.   
  9. __author = [  
  10.     '"yangfei" <yangfei@ptmind.com>'  
  11. ]  
  12.   
  13. #该方法主要用于写入300行WARN日志  
  14. def writeWarnLog(file):  
  15.     count=0;  
  16.     while count<300:  
  17.         try:  
  18.             file.write('2012-11-28 22:51:01|zookeeper|WARN|m1|172.17.1.15\n')  
  19.             count+=1  
  20.         except Exception ,e:  
  21.             print 'write warn log error',str(e)  
  22.             break  
  23.     print 'write warn log finished'  
  24.       
  25. #该方法主要用于写入100行ERROR日志  
  26. def writeErrorLog(file):  
  27.     count=0;  
  28.     while count<100:  
  29.         try:  
  30.             file.write('2012-12-12 22:22:22|zookeeper|ERROR|m1|all\n')  
  31.             count+=1  
  32.         except Exception ,e:  
  33.             print 'write error log error',str(e)  
  34.             break  
  35.     print 'write error log finished'  
  36.               
  37. def main():  
  38.     fileName='zookeeper.log'  
  39.     mode='w+'         #通过追加写日志文件  
  40.     #创建两个线程来写文件  
  41.     try:     
  42.         f=open(fileName,mode)  
  43.         t1=threading.Thread(target=writeWarnLog,args=(f))  
  44.         t2=threading.Thread(target=writeErrorLog,args=(f))  
  45.       
  46.         t1.start()  
  47.         t2.start()  
  48.       
  49.         t1.join()  
  50.         t2.join()  
  51.     except Exception,e:  
  52.         print 'write log failed,',str(e)  
  53.     finally:  
  54.         f.close()  
  55.     print 'write log finished'  
  56.       
  57. if __name__=='__main__':  
  58.     main()  
# -*- coding: utf-8 -*-

import threading

'''
多线程生成日志工具
'''

__author = [
    '"yangfei" <yangfei@ptmind.com>'
]

#该方法主要用于写入300行WARN日志
def writeWarnLog(file):
    count=0;
    while count<300:
        try:
            file.write('2012-11-28 22:51:01|zookeeper|WARN|m1|172.17.1.15\n')
            count+=1
        except Exception ,e:
            print 'write warn log error',str(e)
            break
    print 'write warn log finished'
    
#该方法主要用于写入100行ERROR日志
def writeErrorLog(file):
    count=0;
    while count<100:
        try:
            file.write('2012-12-12 22:22:22|zookeeper|ERROR|m1|all\n')
            count+=1
        except Exception ,e:
            print 'write error log error',str(e)
            break
    print 'write error log finished'
            
def main():
    fileName='zookeeper.log'
    mode='w+'         #通过追加写日志文件
    #创建两个线程来写文件
    try:   
        f=open(fileName,mode)
        t1=threading.Thread(target=writeWarnLog,args=(f))
        t2=threading.Thread(target=writeErrorLog,args=(f))
    
        t1.start()
        t2.start()
    
        t1.join()
        t2.join()
    except Exception,e:
        print 'write log failed,',str(e)
    finally:
        f.close()
    print 'write log finished'
    
if __name__=='__main__':
    main()
这上面的代码存在Bug,直接运行的话,会出现如下错误信息:
Java代码 复制代码 收藏代码
  1. Exception in thread Thread-2:  
  2. Traceback (most recent call last):  
  3.   File "/opt/python/lib/python2.7/threading.py", line 551, in __bootstrap_inner  
  4.     self.run()  
  5.   File "/opt/python/lib/python2.7/threading.py", line 504, in run  
  6.     self.__target(*self.__args, **self.__kwargs)  
  7. TypeError: writeErrorLog() takes exactly 1 argument (0 given)  
  8.   
  9. Exception in thread Thread-1:  
  10. Traceback (most recent call last):  
  11.   File "/opt/python/lib/python2.7/threading.py", line 551, in __bootstrap_inner  
  12.     self.run()  
  13.   File "/opt/python/lib/python2.7/threading.py", line 504, in run  
  14.     self.__target(*self.__args, **self.__kwargs)  
  15. TypeError: writeWarnLog() takes exactly 1 argument (0 given)  
Exception in thread Thread-2:
Traceback (most recent call last):
  File "/opt/python/lib/python2.7/threading.py", line 551, in __bootstrap_inner
    self.run()
  File "/opt/python/lib/python2.7/threading.py", line 504, in run
    self.__target(*self.__args, **self.__kwargs)
TypeError: writeErrorLog() takes exactly 1 argument (0 given)

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/opt/python/lib/python2.7/threading.py", line 551, in __bootstrap_inner
    self.run()
  File "/opt/python/lib/python2.7/threading.py", line 504, in run
    self.__target(*self.__args, **self.__kwargs)
TypeError: writeWarnLog() takes exactly 1 argument (0 given)
异常是说,两个线程的执行的方法需要一个参数,而我并没有给参数,但是通过实际代码查看,明明是都给了一个参数:
Java代码 复制代码 收藏代码
  1. t1=threading.Thread(target=writeWarnLog,args=(f))  
  2. t2=threading.Thread(target=writeErrorLog,args=(f))  
t1=threading.Thread(target=writeWarnLog,args=(f))
t2=threading.Thread(target=writeErrorLog,args=(f))
刚开始我遇到这个问题,感觉很奇怪,明明是给了参数的,但是为什么还说,没有提供参数呢??代码逻辑上也没有错啊,搞不定! 然后查询了Python的API,发现关于args的说明是这样的: args is the argument tuple for the target invocation. Defaults to (). 就是说,这个args是个元组,必须传一个元组,而我这里给的(f)并不是一个元组,如果元组只有一个元素时,格式应该是(element,),不能少了那个逗号,也就是说上门两行代码应该写成如下格式:
Java代码 复制代码 收藏代码
  1. t1=threading.Thread(target=writeWarnLog,args=(f,))  
  2. t2=threading.Thread(target=writeErrorLog,args=(f,))  
t1=threading.Thread(target=writeWarnLog,args=(f,))
t2=threading.Thread(target=writeErrorLog,args=(f,))
修改之后,执行成功,不小心导致的,坑爹啊! 但是! 我试了一下,如果把那两行代码中,参数改为数组格式,照样执行成功,即:
Java代码 复制代码 收藏代码
  1. t1=threading.Thread(target=writeWarnLog,args=[f])  
  2. t2=threading.Thread(target=writeErrorLog,args=[f])  
t1=threading.Thread(target=writeWarnLog,args=[f])
t2=threading.Thread(target=writeErrorLog,args=[f])

posted on 2017-09-06 00:41  myworldworld  阅读(3043)  评论(0)    收藏  举报

导航