1. # =============================操作系统模块=======================
    # 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())
  2.  
  3. # ======================日志=====================
    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")
  4.  
  5. # 日志函数处理日志
    # 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")
  6.  
  7. # ===========================生成和修改常见配置文档==================
    # 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')
  8.  
  9. # =======================匹配与正则表达式===========================
    # 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 匹配一个特殊字符边界,也就是指单词和空格间的位置
  10.  
  11. # -----------------------------------------
    # 结论: * 等价于{0,正无穷} + 等价于{1,正无穷} ? 等价于{0,1}
    # -----------------------------------------
  12.  
  13. # -----------------正则表达式的方法-------------
    # 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)
  14.  
  15. # ========================模块============================
    # 一个.py文件就为一个模块
    # import calculate
    # import sys
    # print(sys.path)
    # print(sys.platform)
    # print(calculate.add(1,2,3,4,5))
  16.  
  17. # ======================JSON 或者 Pickle 或者 shelve=============================
    # import json
  18.  
  19. # dt = {'12':'asdf'}
    # data = json.dumps(dt)
    # with open('18.txt','w') as fd:
    # fd.write(data)
  20.  
  21. # with open('18.txt','r') as fd:
    # data = fd.read()
    # data = json.loads(data)
    # print(data)
    # print(type(data))
  22.  
  23. # import pickle
    # def foo():
    # print("ok")
    # data = pickle.dumps(foo)
    # with open('18.txt','wb') as fd:
    # fd.write(data)
  24.  
  25. # with open('18.txt','rb') as fd:
    # data = fd.read()
    # data = pickle.loads(data)
    # print(type(data))
    # print(data)
    # data()
  26.  
  27. # import shelve
    # f = shelve.open('19.txt')
    # f['info'] = {'name':'alex','age':'18'}
    # print(f.get('info')['name'])
  28.  
  29. # d = {'name':'alex','age':'18'}
    # print(d.get('sex','male'))
  30.  
  31. # 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)
  32.  
  33. # =========================执行命令其他进程并返回值====================================
    # import subprocess
    #
    # obj = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE) #将子进程转移到主进程
    # print(obj)
    # print(obj.stdout)
    # print(str(obj.stdout.read(),'gbk'))
  34.  
  35. # ==========================字符编码=================================
    # str : unicode
    # bytes : 16进制
  36.  
  37. # ===========================线程进程模块=============================
    # ---------------- 普通锁 --------------------
    # 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)
  38.  
  39. # 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()
  40.  
  41. # ------------------递归锁--------------------------------
  42.  
  43. # 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====')
  44.  
  45. # -------------------信号量----------------------------
  46.  
  47. # 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()
  48.  
  49. # -------------------------------条件变量------------------------------------
  50.  
  51. # 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()

Python学习历程之模块浅识的更多相关文章

  1. Python学习 Part4:模块

    Python学习 Part4:模块 1. 模块是将定义保存在一个文件中的方法,然后在脚本中或解释器的交互实例中使用.模块中的定义可以被导入到其他模块或者main模块. 模块就是一个包含Python定义 ...

  2. python学习之argparse模块

    python学习之argparse模块 一.简介: argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块.argparse模块的作用是用于解析命令行 ...

  3. Python学习day19-常用模块之re模块

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  4. Python学习day18-常用模块之NumPy

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  5. python学习之random模块

    Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. random.random random.random()用于生成一个0到1的随机符点数: 0 < ...

  6. Python学习笔记之模块与包

    一.模块 1.模块的概念 模块这一概念很大程度上是为了解决代码的可重用性而出现的,其实这一概念并没有多复杂,简单来说不过是一个后缀为 .py 的 Python 文件而已 例如,我在某个工作中经常需要打 ...

  7. Python学习笔记-常用模块

    1.python模块 如果你退出 Python 解释器并重新进入,你做的任何定义(变量和方法)都会丢失.因此,如果你想要编写一些更大的程序,为准备解释器输入使用一个文本编辑器会更好,并以那个文件替代作 ...

  8. Python学习笔记1—模块

    模块的使用 引用模块的两种形式 形式一: import module_name 形式二: from module1 import module11   (module11是module的子模块) 例: ...

  9. Python学习笔记2——模块的发布

    1.为模块nester创建文件夹nester,其中包含:nester.py(模块文件): """这是"nester.py"模块,提供了一个名为prin ...

随机推荐

  1. 备忘录模式(Memento)C++实现

    备忘录模式 意图: 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态.这样以后就可将改对象恢复到原先保存的状态. 适用性: 1.必须保存一个对象在某一个时刻的部分状态,这样以 ...

  2. WindowsNT设备驱动程序开发基础

    一.背景介绍 1.1WindowsNT操作系统的组成1.1.1用户模式(UserMode)与内核模式(KernelMode) 从Intel80386开始,出于安全性和稳定性的考虑,该系列的CPU可以运 ...

  3. LeetCode 287. Find the Duplicate Number (python 判断环,时间复杂度O(n))

    LeetCode 287. Find the Duplicate Number 暴力解法 时间 O(nlog(n)),空间O(n),按题目中Note"只用O(1)的空间",照理是过 ...

  4. fopen函数打开文件总是返回NULL错误

    有时候,调用fopen函数用来打开文件,但是总会返回NULL.对于此类问题.一定是一下两种原因之一造成的. 1.路径错误.(路径中斜杠和反斜杠的问题) 2.文件在另一个进程中被打开,再次打开当然不行( ...

  5. 杭电 1040 As Easy As A+B 【排序】

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1040 解题思路:数据不大,可以直接用冒泡排序 #include<stdio.h> int ...

  6. iOS runLoop 原理多线程 总结 NSTimer优化

    可以理解为字面意思:Run 表示运行,Loop 表示循环.结合在一起就是运行的循环的意思.哈哈,我更愿意翻译为『跑圈』.直观理解就像是不停的跑圈. RunLoop 实际上是一个对象,这个对象在循环中用 ...

  7. Matrix Matcher UVA - 11019AC_自动机 + 代价提前计算

    Code: #include<cstdio> #include<cstring> #include<algorithm> #include<vector> ...

  8. css3 3d  魔方

    <style><!--@charset "UTF-8"; * { margin: 0; padding: 0 } html,body{ width: 100%; ...

  9. bzoj 2834: 回家的路

    题目 F.A.Qs Home Discuss ProblemSet Status Ranklist Contest 入门OJ ModifyUser  DCOI Logout 捐赠本站 Notice:1 ...

  10. SpringMVC的DispatcherServlet加载过程

    首先在web.xml中配置容器启动监听器,这样在容器启动后Spring会初始化一个ServletContext,负责加载springmvc的九大组件(调用DispatcherServlet.onRef ...