Python操作日志、加密、发送邮件、线程、生产者消费者


1、操作日志


logging.basicConfig:日志的统一处理器,对日志的输出格式和方式做配置
日志级别等级CRITICAL > ERROR > WARNING > INFO > EDBUG


level设定级别以及以上级别的才会打印,这里注意大小写!


打印日志信息在控制台或输出在一个文件示例:


 1 import logging
 2 import os
 3 
 4 # log_file = os.path.join(os.getcwd(),'wlog.log')
 5 log_format = "%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s: %(message)s"
 6 '''
 7 如果不写filename和filemode参数则默认打印到console
 8 '''
 9 logging.basicConfig(level=logging.WARNING,format=log_format)
10 # logging.basicConfig(level=logging.WARNING,format=log_format,filename=log_file,filemode='w')
11 
12 logging.warning("waring message")
13 logging.error("error message")

输出在控制台信息如下:


2017-03-20 21:41:07,756 3.19.py [line:24] WARNING: waring message
2017-03-20 21:41:07,756 3.19.py [line:25] ERROR: error message


同时在控制台和输出到文件代码示例:


 1 # 创建一个logger
 2 logger = logging.getLogger("mylogger")
 3 logger.setLevel(logging.INFO)
 4 
 5 # 创建一个handler,将log写入文件中
 6 fh = logging.FileHandler('D:/pycharm workspace/practice/log.txt','a')
 7 fh.setLevel(logging.INFO)
 8 
 9 # 再创建一个handler,将log输出在控制台
10 ch = logging.StreamHandler()
11 ch.setLevel(logging.CRITICAL)
12 
13 # 设置输出格式
14 log_format = "%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s: %(message)s"
15 formatter = logging.Formatter(log_format)
16 fh.setFormatter(formatter)
17 ch.setFormatter(formatter)
18 
19 #把handler添加到logger里,其实可以理解为汇报给大领导
20 logger.addHandler(fh)
21 logger.addHandler(ch)
22 
23 logger.error("今天天气阴")

控制台设置为CRITICAL不会有输出,因为打印的是error信息
输出到文件设置为INFO,打印的是error信息,会输出在文件中
如果设置成不一样的实际是没有任何意义。一般都设置为INFO。


另:


将执行脚本的日志保存在一个文件中


1     dirfile = os.listdir("D:\\")
2     for i in dirfile:
3         s=i.split('.')[1]
4         print(s)
5         if s == "py":
6             os.system("D:\\%s 1>>log.txt 2>&1" %i)

 


2、加密


#DES加密
# pyDes.des(key,[mode],[IV],[pad],[pdamode])
# 参数的意思分别如下:
# key:加密密钥,长度为8位。必选
# mode:加密方式。ECB(默认)、CBC(安全性好于前者)
# IV:初始字节数(长度为8位),如果选择的加密方式为CBC必须有这个参数。否则可以没有
# pad:加密时,将该字符添加到数据块的结尾;解密时,将删除从最后一个往前的8位
# padmode:PAD_NORMAL、PAD_PKCSS,当选择前者时必须设置pad


md5、sha、des加密代码示例:


 1 import hashlib     #md5 sha
 2 import base64      #des
 3 from pyDes import *
 4 
 5 def md5_encode(data):
 6     m = hashlib.md5()
 7     m.update(data.encode('utf-8'))
 8     return m.hexdigest()     #经过特殊处理之后以字符串形式返回
 9 
10 def sha1_encode(data):
11     sha1 = hashlib.sha1()
12     sha1.update(data.encode('utf-8'))
13     return sha1.hexdigest()
14 
15 def des_encode(data):
16     k = des("xqtest66",padmode=PAD_PKCS5)
17     # k = des('xqtest66',CBC,'goodluck',pad='hahahaha',padmode=PAD_NORMAL)
18 
19     #encrypt来加密我的数据,然后进行base64编码
20     encodeStrr = base64.b64encode(k.encrypt(data))
21     return encodeStrr
22 
23 data = "wo"
24 print('md5加密结果:',md5_encode(data))
25 print('sha加密结果:',sha1_encode(data))
26 print('des加密结果:',des_encode(data))

3、发送邮件


 1 import smtplib
 2 import email.mime.multipart
 3 import email.mime.text
 4 
 5 from email.mime.application import MIMEApplication
 6 
 7 class SendMail:
 8     def send_mail(self,title):
 9         msg = email.mime.multipart.MIMEMultipart() #生成包含多个邮件体的对象
10         msg['from'] = 'jiayan****@126.com'
11         msg['to'] = '5478987@qq.com'
12         msg['subject'] = title
13         content = '''
14         这是邮件的正文部分
15         '''
16 
17         #邮件正文
18         txt = email.mime.text.MIMEText(content)
19         msg.attach(txt)
20 
21         #excel附件
22         # xlsxpart = MIMEApplication(open('send_mail_excel.xlsx', 'rb').read())
23         # xlsxpart.add_header('Content-Disposition', 'attachment', filename='send_mail_excel.xlsx')
24         # msg.attach(xlsxpart)
25 
26         #jpg图片附件
27         jpgpart = MIMEApplication(open('Aaron.png', 'rb').read())
28         jpgpart.add_header('Content-Disposition', 'attachment', filename='Aaron.png')   #需要图片文件在代码相应的目录下
29         msg.attach(jpgpart)
30 
31         #发送邮件
32         smtp=smtplib
33         smtp=smtplib.SMTP()
34         smtp.set_debuglevel(1)            #设置为调试模式,console中显示
35         smtp.connect('smtp.126.com','25') #链接服务器,smtp地址+端口
36         smtp.login('jiayan****@126.com','Jiaxxxxxxxx')                   #登录,用户名+密码
37         smtp.sendmail('jiayan****@126.com','5478987@qq.com',str(msg)) #发送,from+to+内容
38         smtp.quit()
39 
40 mail = SendMail()
41 mail.send_mail('python自动化测试')

 查找最进时间修改的文件,代码如下:


 1 os.path.listdir  #以列表的形式展示文件
 2 os.path.getmtime #最后修改的时间
 3 os.path.join     #路径拼接
 4 
 5 import os
 6 filenames = "D:\\pycharm workspace\\appiumframework\\report"
 7 lists = os.listdir(filenames)
 8 print(lists)
 9 lists.sort(key=lambda fn:os.path.getmtime(filenames+"\\"+fn))
10 print(lists[-1])
11 file = os.path.join(filenames,lists[-1])
12 print(file)

4、进程与线程的区别:

进程不共享空间,线程共享地址空间

线程共享空间优缺点:
优点:多线程给用户的体验好些,处理速度快些
缺点:共享地址空间相互影响

 1 import threading
 2 import time
 3 
 4 class Mythreading(threading.Thread):
 5     def __init__(self,threadID,name,counter):
 6         threading.Thread.__init__(self)    #固定格式
 7         self.threadID = threadID
 8         self.name = name
 9         self.counter = counter
10         print("初始化完成")
11     def run(self):                         #由cpu来处理决定线程间的执行顺序
12         print("开始"+self.name)
13         print_time(self.name,self.counter,5)
14         print("结束"+self.name)
15 
16 def print_time(threasName,counter,delay):
17     while counter:
18         time.sleep(delay)
19         print("%s:%s"%(threasName,time.ctime(time.time())))
20         counter -= 1
21 
22 #创建线程
23 thread1 = Mythreading(1,"thread1",1)
24 thread2 = Mythreading(2,"thread2",2)
25 
26 #开启线程
27 thread1.start()
28 thread2.start()
 1 import threading
 2 import time
 3 
 4 class Mythreading(threading.Thread):
 5     def __init__(self,threadID,name,counter):
 6         threading.Thread.__init__(self)    #固定格式
 7         self.threadID = threadID
 8         self.name = name
 9         self.counter = counter
10         print("初始化完成")
11     def run(self):                         #由cpu来处理决定线程间的执行顺序
12         threadLock.acquire()               #获得锁,成功获得锁定后返回True,可选的参数timeout不填时将一直阻塞直到获得锁定
13         print_time(self.name,self.counter,3)
14         threadLock.release()               #释放锁,开始下一个线程
15 
16 def print_time(threasName,counter,delay):
17     while counter:
18         time.sleep(delay)
19         print("%s:%s"%(threasName,time.ctime(time.time())))
20         counter -= 1
21 
22 threadLock = threading.Lock()
23 threads = []
24 
25 #创建线程
26 thread1 = Mythreading(1,"thread1",1)
27 thread2 = Mythreading(2,"thread2",2)
28 
29 #开启线程
30 thread1.start()
31 thread2.start()
32 
33 # thread1.join()
34 # thread2.join()
35 threads.append(thread1)
36 threads.append(thread2)
37 for t in threads:
38     t.join()       #后边的代码必须等待,等线程运行完成才会往后运行代码
39 
40 print("我的的花儿也谢了")

为什么下图左为串行,下图右为并行运行呢?

图左love启动后分别执行start和join,启动了join后边代码就需要等待前边代码运行完成。总共18s

图右同时启动love和hate,运行所需要执行的时间然后停止。总共10s

 超级播放器示例,如下:

 1 import threading
 2 from time import sleep, ctime
 3 def music(func):
 4     for i in range(2):
 5         print ("I was listening to %s! %s" %(func,ctime()))
 6         sleep(4)
 7 def move(func):
 8     for i in range(2):
 9         print ("I was at the %s! %s" %(func,ctime()))
10         sleep(5)
11 
12 def player(name):
13     r = name.split('.')[1]
14     if r=="mp3":
15         music(name)
16     elif r=="mp4":
17         move(name)
18     else:
19         print("%s is error!"%name)
20 
21 lists = ["love.mp3","hate.mp4","cuicui.mp3","nnnn.mp4"]
22 
23 threads = []
24 files = range(len(lists))
25 for i in files:
26     t = threading.Thread(target=player,args=(lists[i],))
27     threads.append(t)
28 
29 if __name__ == '__main__':
30     for i in files:
31         threads[i].start()
32     for i in files:
33         threads[i].join()
34     print ('all end: %s' %ctime())

 

5、生产者与消费者示例:

 1 import threading
 2 class Produce(threading.Thread):
 3 
 4     def __init__(self,name):
 5         threading.Thread.__init__(self)
 6         self.name = name
 7     def run(self):
 8         global x
 9         tt.acquire()
10         if x > 0 :
11 
12             print("我不生产了")
13         else:
14             for i in range(5):
15                 x += 1
16                 print("%s在生产中,第%d个"%(self.name,x))
17         tt.release()
18 
19 class Consume(threading.Thread):
20     def __init__(self,name):
21         threading.Thread.__init__(self)
22         self.name = name
23     def run(self):
24         global x
25         tt.acquire()
26         if x == 0:
27 
28             print("我不消费了")
29         else:
30             for i in range(5):
31                 x -= 1
32                 print("%s在消费中,第%d个"%(self.name,x+1))
33         tt.release()
34 x = 0
35 tt = threading.Lock()
36 # tt = threading.Condition
37 
38 p = Produce("produce")
39 c = Consume("consume")
40 
41 p.start()
42 c.start()
43 
44 p.join()
45 c.join()
posted @ 2017-12-21 00:26  海布里Simple  阅读(952)  评论(0编辑  收藏  举报