# -*- coding: utf-8 -*-
# @Time : 2020/2/23 18:29
# @File : 01.py
import pickle
person = {'name': 'Tom', 'age': 20}
# 将对象序列化
s = pickle.dumps(person)
print(s)
# 反序列化
p = pickle.loads(s)
print(p)
# 保存为二进制文件
pickle.dump(person, open('pickle_db', 'wb'))
# 从文件载入
p = pickle.load(open('pickle_db', 'rb'))
# 将多个对象存储在一个文件中
import shelve
scores = [99, 88, 77]
student = {'name': 'Tom', 'age': 20}
db = shelve.open('shelve_student')
db['s'] = student
db['score'] = scores
db.close()
# 正则
import re
text = 'Tom is 8years old. Mike is 10 years old'
pattern = re.compile('\d+')
re.findall('\d+', text)
print(pattern.findall(text))
import re
s = '\\author:Tom'
# 加转义符
pattern = re.compile(r'\\author')
print(pattern.findall(s))
import re
text = 'Tom is 8 years old. Mike is 23 years old. Peter is 78 years old.'
pattern =re.compile(r'\d+')
print(pattern.findall(text))
p_name = re.compile(r'[A-Z]\w+')
print(p_name.findall(text))
p_age = re.compile('\\d+')
print(p_age.findall(text))
import re
text = 'Beautiful is better than ugly.\nExplicit is better than implicit.\n Simple is better than complex'
p = re.compile(r'\n')
p.split(text)
re.split(r'\n', text)
# 利用分组将分割符号保留
re.split(r'(-)', 'Good-Morning')
# 保留前1组,剩下的为整体
re.split(r'\n', text, 1)
import re
ords = 'ORD001\nORD002\nORD003'
#替换字符
re.sub(r'\d+', '-', ords)
# 替换原有格式
re.sub(r'([A-Z]+)(\d+)', '\g<2>-\g<1>', ords)
# 替换字符---g<1>保留分组的内容,表现内引用
text = 'Beautiful is better than ugly.'
re.sub(r'\*(.*?)\*', '<strong>\g<1></strong>', text)
# 替换字符---?P<html>定义分组名称
re.sub(r'\*(?P<html>.*?)\*', '<strong>\g<html></strong>', text)
# 忽略大小写
text = 'Python PYthon PYTHON'
re.findall(r'python', text, re.I)
# 单线程示例
import time
def worker(n):
print('函数开始于:{}'.format(time.ctime()))
time.sleep(n)
print('函数结束于:{}'.format(time.ctime()))
def main():
print('主函数开始于:{}'.format(time.ctime()))
worker(4)
worker(2)
print('主函数结束于:{}'.format(time.ctime()))
main()
# _thread 实现多线程
import time
import _thread
def worker(n):
print('函数开始于:{}'.format(time.ctime()))
time.sleep(n)
print('函数结束于:{}'.format(time.ctime()))
def main():
print('主函数开始于:{}'.format(time.ctime()))
_thread.start_new_thread(worker, (4,))
_thread.start_new_thread(worker, (2,))
time.sleep(6)
print('主函数结束于:{}'.format(time.ctime()))
main()
# threading.Thread() 实现多线程
import time
from threading import Thread, current_thread
def worker(n):
print('{}函数开始于:{}'.format(current_thread().name, time.ctime())) # 获取当前线程
time.sleep(n)
print('{}函数结束于:{}'.format(current_thread().name, time.ctime()))
def main():
print('主函数开始于:{}'.format(time.ctime()))
threads = []
t1 = Thread(target=worker, args=(4,))
threads.append(t1)
t2 = Thread(target=worker, args=(2,))
threads.append(t2)
for t in threads:
t.start()
for t in threads:
t.join()
print('主函数结束于:{}'.format(time.ctime()))
main()
# threading.Thread 派生类实现多线程
import time
from threading import Thread, current_thread
class MyThread(Thread):
def __init__(self, func, args):
Thread.__init__(self)
self.func = func
self.args = args
def run(self):
self.func(*self.args)
def worker(n):
print('{}函数开始于:{}'.format(current_thread().name, time.ctime())) # 获取当前线程
time.sleep(n)
print('{}函数结束于:{}'.format(current_thread().name, time.ctime()))
def main():
print('主函数开始于:{}'.format(time.ctime()))
threads = []
t1 = MyThread(worker, (4,))
threads.append(t1)
t2 = MyThread(worker, (2,))
threads.append(t2)
for t in threads:
t.start()
for t in threads:
t.join()
print('主函数结束于:{}'.format(time.ctime()))
main()
锁
import threading
import time
import random
eggs = []
lock = threading.Lock()
def put_egg(n, lst):
# lock.acquire()#加锁
# for i in range(1, n + 1):
# time.sleep(random.randint(0, 1))
# lst.append(i)
# lock.release()#释放
# ---------------
with lock:
for i in range(1, n + 1):
time.sleep(random.randint(0, 1))
lst.append(i)
def main():
threads = []
for i in range(3):
t = threading.Thread(target=put_egg, args=(5, eggs))
threads.append(t)
for t in threads:
t.start()
for t in threads:
t.join()
print(eggs)
if __name__ == '__main__':
main()
# 队列,先进先出示例
import threading
import queue
import time
import random
def producer(data_queue):
for i in range(5):
time.sleep(0.5)
item = random.randint(1, 100)
data_queue.put(item)
print(f'{threading.current_thread().name} 在队列中放入数据项:{item}')
def consumer(data_queue):
while True:
try:
item = data_queue.get(timeout=3)
print(f'{threading.current_thread().name} 从队列移除了{item}')
except queue.Empty:
break
else:
data_queue.task_done()
def main():
q = queue.Queue()
threads = []
p = threading.Thread(target=producer, args=(q,))
p.start()
for i in range(2):
c = threading.Thread(target=consumer, args=(q,))
threads.append(c)
for t in threads:
t.start()
for t in threads:
t.join()
q.join()
main()
# 多进程示例
import time
import multiprocessing
def func(n):
print(f'{multiprocessing.current_process().name},开始于{time.ctime()}')
time.sleep(n)
print(f'{multiprocessing.current_process().name},结束于{time.ctime()}')
def main():
print(f'主函数运行于:{time.ctime()}')
processes = []
p1 = multiprocessing.Process(target=func, args=(4,))
processes.append(p1)
p2 = multiprocessing.Process(target=func, args=(2,))
processes.append(p2)
for p in processes:
p.start()
for p in processes:
p.join()
print(f'主函数结束于:{time.ctime()}')
if __name__ == '__main__':
main()
# concurrent.futures示例
import time
import concurrent.futures
nums = list(range(1, 11))
def count(n):
for i in range(10000000):
i += i
return i * n
def worker(x):
res = count(x)
print(f'数字{x}的计算结果是:{res}')
# 顺序执行
def sequential_execution():
start_time = time.clock()
for i in nums:
worker(i)
print(f'顺序执行花费时间{time.clock() - start_time}秒')
# 线程池执行
def threading_execution():
start_time = time.clock()
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
for i in nums:
executor.submit(worker, i)
print(f'顺序执行花费时间{time.clock() - start_time}秒')
# 进程池执行
def process_execution():
start_time = time.clock()
with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:
for i in nums:
executor.submit(worker, i)
print(f'顺序执行花费时间{time.clock() - start_time}秒')
if __name__ == '__main__':
process_execution()