转载自:http://michael8335.iteye.com/blog/1738485
由于最近一段时间,学了一门脚本语言-Python,原因是一、公司需要;二、只掌握Java感觉还是不够。
由于需要用python分析日志,但是日志实际还没有,格式已经定了,所以我先用python写了个多线程写文件的工具,比较简单,作为一个学习总结吧,同时还遇到了一个问题,顺便将问题和解决方法也总结一下。
需求:两个线程同时向一个文件中写固定格式的文件
实际代码:
# -*- coding: utf-8 -*- import threading ''' 多线程生成日志工具 ''' __author = [ '"yangfei" <[email protected]>' ] #该方法主要用于写入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()
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,))
t1=threading.Thread(target=writeWarnLog,args=[f]) t2=threading.Thread(target=writeErrorLog,args=[f])