多线程写文件实例
Python多线程写文件实例 博客分类:
由于最近一段时间,学了一门脚本语言-Python,原因是一、公司需要;二、只掌握Java感觉还是不够。 由于需要用python分析日志,但是日志实际还没有,格式已经定了,所以我先用python写了个多线程写文件的工具,比较简单,作为一个学习总结吧,同时还遇到了一个问题,顺便将问题和解决方法也总结一下。 需求:两个线程同时向一个文件中写固定格式的文件 实际代码:
- # -*- 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()
# -*- 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,直接运行的话,会出现如下错误信息:
- 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)
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)异常是说,两个线程的执行的方法需要一个参数,而我并没有给参数,但是通过实际代码查看,明明是都给了一个参数:
- t1=threading.Thread(target=writeWarnLog,args=(f))
- 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,),不能少了那个逗号,也就是说上门两行代码应该写成如下格式:
- t1=threading.Thread(target=writeWarnLog,args=(f,))
- t2=threading.Thread(target=writeErrorLog,args=(f,))
t1=threading.Thread(target=writeWarnLog,args=(f,)) t2=threading.Thread(target=writeErrorLog,args=(f,))修改之后,执行成功,不小心导致的,坑爹啊! 但是! 我试了一下,如果把那两行代码中,参数改为数组格式,照样执行成功,即:
- t1=threading.Thread(target=writeWarnLog,args=[f])
- 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) 收藏 举报