Python学习历程之模块浅识

# =============================操作系统模块=======================
# import os
# 待续
# ==============================解释器模块========================
# import sys
# 待续
# ===============================加密============================
# import hashlib
#
# m = hashlib.md5()
# m.update("HelloWorld".encode("utf8"))
# print(m.hexdigest())
#
# s = hashlib.sha256()
# s.update("HelloWorld".encode("utf8"))
# print(s.hexdigest())

# ======================日志=====================
import logging
# 日志配置
# logging.basicConfig(level=logging.DEBUG,
# format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
# datefmt='%a,%d %b %Y %H:%M:%S',
# filename='test.log',
# filemode='a')
#
# logging.debug("degub message")
# logging.info("info message")
# logging.warning("warning message")
# logging.error("error message")
# logging.critical("critical message")

# 日志函数处理日志
# logging.basicConfig(level=logging.DEBUG)
# logger = logging.getLogger()
# #创建一个handler 用于写入日志文件
# fh = logging.FileHandler('test.log')
# #在创建一个handler,用于输出到控制台
# ch = logging.StreamHandler()
#
# formamtter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#
# fh.setFormatter(formamtter)
# ch.setFormatter(formamtter)
#
# logger.addHandler(fh)
# logger.addHandler(ch)
#
# logger.debug("degub message")
# logger.info("info message")
# logger.warning("warning message")
# logger.error("error message")
# logger.critical("critical message")

# ===========================生成和修改常见配置文档==================
# import configparser
#
# config = configparser.ConfigParser()
# 创建配置文件 example.ini ,写入数据
# config['DEFAULT']={'ServerAliveInterval':'45',
# 'Compression':'yes',
# 'CompressionLevel':'9'}
# config['bitbucket.org']={}
# config['bitbucket.org']['User']='hg'
#
# with open('example.ini','w') as configfile:
# config.write(configfile)
# 读取配置文件得数据
# config.read('example.ini')
# print(config.sections())
# print(config.defaults())
# 判断数据是否在配置文件中
# print('bitbucket.org' in config)
# print('bitbucke' in config)
# 单独取值
# print(config['bitbucket.org']['user'])
# 循环取值
# for key in config['bitbucket.org']:
# print(key) # 还默认打印Default里面得东西
# 复制粘贴
# config.remove_section('topsecret.server.com')#删除块
# config.remove_option('bitbucket.org','user') # 删除模块下的键值对
# config.write(open('example.ini','w'))
# 修改
# config.set('bitbucket.org','user','alex')

# =======================匹配与正则表达式===========================
# string提供的方法是完全匹配
# s = 'hello world'
# print(s.find('llo'))
# ret = s.replace('ll','xx')
# print(ret)
# print(s.split(' '))
# print(s.split('w'))
# 正则表达式提供的方法是模糊匹配
# 字符匹配(普通字符,元字符):
# 普通字符:大多数的字符和字母都会和自身匹配
# 2元字符: . ^ $ * + ? { } [ ] | ( ) \
# import re
# ---------- . : 通配符 -------------
# res =re.findall('w\w{2}l','hello world') # 匹配的内容
# res = re.findall('alex','adfsfsdkljblldfsdf')
# res = re.findall('w..l','hello world') # . 代之所有的一个字符除了换行符
# res = re.findall('w.l','hello w \nld')
# --------- ^ : 尖角符 ----------------
# res = re.findall('^h...o','hjasdhello') # ^ 开头匹配
# --------- $ : dollar符 -----------------
# res = re.findall('a..x$','sdfsalex') # $ 结尾匹配
# --------- * :星符 ---------------
# res = re.findall('a.*li','fsdfsfasdfsfsdlisdfsdfse') # 重复匹配[0,+oo]
# --------- + : 加号符 --------------
# res = re.findall('b+','kajsfbhbbb') # 匹配[1,+oo]个前面的字符
# --------- ? :问好符 -------------
# res = re.findall('ab?','adfsfab') # 匹配[0,1]个前面的字符
# --------- { } :大括号符 ------------
# res = re.findall('a{5}b','aaaaabaaab') # 匹配指定次数的字符
# res = re.findall('a{1,3}b','abaabaaabaaaab') # 匹配指定范围数的字符
# --------- [ ] :中括号符(字符集) ------------
# res = re.findall('a[c,b]x','acx') # 字符集合 或者的关系,只能选一种
# res = re.findall('a[a-z]x','azx') # [a-z] :a,b,c,d...x,y,z
# res = re.findall('a[.*|]x','adbsa|xsda.xfa*xdfsf') # 取消元字符的特殊功能除了(\ ^ -)
# res = re.findall('[1-9,a-z,A-Z]','12tyAS') #全部匹配
# res = re.findall('[1-9a-zA-Z]','12tyAS') #全部匹配
# res = re.findall('[^t]','12tyAS') # ^ 在 []中求反
# res = re.findall('[^iu]','iusdfsfsdf') # ^ 在 [] 中非的意思
# --------- | : 管道符 ------------
# res = re.search('(as)|3','3asf3').group() # 管道符是或的意思
# --------- ( ) : 括号符 -----------
# res = re.search('(as)+','sdfsasas').group() # 括号是分组
# res = re.search('(?P<id>\d{3})/(?P<name>\w{3})','weew34ttt123/ooo')
# res = re.findall('www.(?:\w+).com','www.baidu.com') # ?: 取消组的优先级
# --------- \ : 斜杠符 -----------
# 反斜杠后边跟元字符去除特殊功能
# 反斜杠后面跟普通字符实现特殊功能
# \d 匹配任意十进制数 [0-9]
# \D 匹配任意非数字字符 [^0-9]
# \s 匹配任意空白字符 [\t\n\r\f\v]
# \S 匹配任意非空白字符 [^\t\n\r\f\v]
# \w 匹配任意字母数字符 [a-zA-Z0-9]
# \W 匹配任意非字母数字符 [^a-zA-Z0-9]
# \b 匹配一个特殊字符边界,也就是指单词和空格间的位置


# -----------------------------------------
# 结论: * 等价于{0,正无穷} + 等价于{1,正无穷} ? 等价于{0,1}
# -----------------------------------------


# -----------------正则表达式的方法-------------
# re.findall() #返回满足条件的所有结果到一个列表里
# re.fullmatch() #全模式匹配
# re.finditer() #返回匹配结果的迭代器
# re.search() # 匹配返回满足条件的第一个结果可以调用group()返回结果
# re.match() #只在字符串开始匹配
# re.split() # 分割
# re.sub() # 替换
# re.subn() # 替换
# obj = re.compile('.com') # 编译成正则对象
# print(res.group())
# print(res.group('id'))
# print(res.group('name'))
# print(res)


# ========================模块============================
# 一个.py文件就为一个模块
# import calculate
# import sys
# print(sys.path)
# print(sys.platform)
# print(calculate.add(1,2,3,4,5))

# ======================JSON 或者 Pickle 或者 shelve=============================
# import json

# dt = {'12':'asdf'}
# data = json.dumps(dt)
# with open('18.txt','w') as fd:
# fd.write(data)

# with open('18.txt','r') as fd:
# data = fd.read()
# data = json.loads(data)
# print(data)
# print(type(data))

# import pickle
# def foo():
# print("ok")
# data = pickle.dumps(foo)
# with open('18.txt','wb') as fd:
# fd.write(data)

# with open('18.txt','rb') as fd:
# data = fd.read()
# data = pickle.loads(data)
# print(type(data))
# print(data)
# data()

# import shelve
# f = shelve.open('19.txt')
# f['info'] = {'name':'alex','age':'18'}
# print(f.get('info')['name'])

# d = {'name':'alex','age':'18'}
# print(d.get('sex','male'))

# class F1:
# def __init__(self):
# self.name = 123
# print('F1',self.name)
# class F2:
# def __init__(self,a):
# self.ff = a
# print('F2',self.ff.name)
#
# class F3:
# def __init__(self,b):
# self.dd = b
# print('F3',self.dd.ff.name)
# f = F1()
# f2 = F2(f)
# f3 = F3(f2)

# =========================执行命令其他进程并返回值====================================
# import subprocess
#
# obj = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE) #将子进程转移到主进程
# print(obj)
# print(obj.stdout)
# print(str(obj.stdout.read(),'gbk'))

# ==========================字符编码=================================
# str : unicode
# bytes : 16进制

# ===========================线程进程模块=============================
# ---------------- 普通锁 --------------------
# import time
# import threading
# begin = time.time()
# def foo():
# print('foo')
# time.sleep(1)
# def bar():
# print('bar')
# time.sleep(2)
# t1 = threading.Thread(target=foo)
# t2 = threading.Thread(target=bar)
# t1.start()
# t2.start()
# end = time.time()
# print(end-begin)

# from time import sleep,ctime
# import threading
#
# num = 1000
# def foo():
# global num
# r.acquire()
# num -= 1
# sleep(0.1)
# r.release()
#
#
# def main():
# begin = ctime()
# print(begin)
# threadList = []
# for i in range(100):
# t=threading.Thread(target=foo())
# threadList.append(t)
# for i in threadList:
# i.start()
# # for i in threadList:
# # i.join()
# end = ctime()
# print(num)
# print(end)
#
# if __name__ == '__main__':
# r = threading.Lock()
# main()

# ------------------递归锁--------------------------------

# import threading
# import time
# class MyThread:
# def doA(self):
# rlock.acquire()
# print('A gets rlock')
# time.sleep(3)
# rlock.acquire()
# print('A gets rlock')
# time.sleep(1)
# rlock.release()
# rlock.release()
# def doB(self):
# rlock.acquire()
# print('B gets rlock')
# time.sleep(2)
# rlock.acquire()
# print('B gets rlock')
# time.sleep(2)
# rlock.release()
# rlock.release()
# def do(self):
# self.doA()
# self.doB()
#
# if __name__ == '__main__':
# # lockA = threading.Lock()
# # lockB = threading.Lock()
# rlock = threading.RLock()
# lockList = []
# for i in range(5):
# t = threading.Thread(target=MyThread().do())
# lockList.append(t)
# for i in lockList:
# i.start()
# for i in lockList:
# i.join()
# print('======end====')

# -------------------信号量----------------------------

# import threading
# import time
#
# class MyThread(threading.Thread):
# def run(self):
# if semaphore.acquire():
# print(self.name)
# time.sleep(2)
# semaphore.release()
#
# if __name__ == '__main__':
# semaphore = threading.BoundedSemaphore(5)
# thrs = []
# for i in range(23):
# thrs.append(MyThread())
# for i in thrs:
# i.start()

# -------------------------------条件变量------------------------------------

# import threading,time
# from random import randint
#
# class Producer(threading.Thread):
# def run(self):
# global L
# while True:
# val=randint(0,100)
# print('生产者',self.name,":Append"+str(val),L)
# if lock_con.acquire():
# L.append(val)
# lock_con.notify()
# lock_con.release()
# time.sleep(3)
# class Consumer(threading.Thread):
# def run(self):
# global L
# while True:
# lock_con.acquire()
# if len(L)==0:
# lock_con.wait()
# print('消费者',self.name,":Delete"+str(L[0]),L)
# del L[0]
# lock_con.release()
# time.sleep(0.25)
#
# if __name__=="__main__":
#
# L=[]
# lock_con=threading.Condition()
# threads=[]
# for i in range(5):
# threads.append(Producer())
# threads.append(Consumer())
# for t in threads:
# t.start()
# for t in threads:
# t.join()
posted @ 2018-10-24 17:00  Weibull  阅读(313)  评论(0编辑  收藏  举报