模块:模块支持从逻辑上组织Python代码,当代码量变得非常大的时候,最好把代码分成一些有组织的代码段。代码片段相互间有一定的联系,可能是一个包含数据成员和方法的类、函数、变量。
搜索路径:模块的导入需要一个叫做‘路径搜索’的过程。Python在文件系统‘预定义区域’中查找要调用的模块。搜索路径在sys.path中定义,也可以通过PYTHONPATH环境变量引入自定义目录。
当匹配搜索到模块就会停止匹配(匹配即停止)

当在/tmp/mylibs中创建.py文件导入该模块就会失败,因为sys.path中没有该路径

使用PYTHONPATH环境变量导入该路径,此时就能成功导入该模块了

hashlib模块:hashlib用来替换md5和sha模块,并使他们的API一致,专门提供hash算法包括md5、sha1、sha224、sha256、sha384、sha512,使用非常简单、方便


分批计算


计算大文件的md5值


tarfile模块:tarfile模块允许创建、访问tar文件同时支持gzip、bzip2格式


解包


面向对象编程基础(oop):面向过程:是一种以事件为中心的编程思想,编程的时候把解决问题的步骤分析出来,然后用函数把这些步骤实现,在一步一步的具体步骤中再按顺序调用函数。面向对象:是一种以“对象"为中心的编程思想,把要解决的问题分解成各个对象,建立对象的目的不是为了完成一个步骤,而是为了描叙某个对象在整个解决问题的步骤中的属性和行为。
面向对象是更大的封装,根据职责在一个对象中封装多个方法和属性。
类和对象:
类:是对一群具有相同特征或者行为的事物的一个统称,是抽象的,不能直接使用。特征被称为属性。行为被称为方法。类就相当于制造飞机时的图纸,是一个模板,是负责创建对象的
对象:是由类创建出来的一个具体存在,可以直接使用由哪一个类创建出来的对象,就拥有在哪一个类中定义的:属性、方法。对象就相当于图纸制造的飞机。
类和对象的关系:类是模板,对象是根据类这个模板创建出来的,应该先有类,再有对象。类只有一个,而对象可以有很多个。不同的对象之间属性可能会各不相同。类中定义了什么属性和方法,对象中就有什么属性和方法,不可能多,也不可能少
面向对象的三大特性:1、封装:根据职责将属性和方法封装到一个抽象的类中。2、继承:实现代码的重用,相同的代码不需要重复的编写。3、多态:不同的对象调用相同的方法,产生不同的执行结果,增加代码的灵活度
创建类:使用class语句来创建一个新类,class 之后为类的名称并以冒号结尾。
构造器方法:当实例化类的对象是,构造器方法默认自动调用实例本身作为第一个参数,传递给self


练习:编写游戏
创建游戏角色类,游戏人物角色拥有名字、武器等属性,游戏人物具有攻击和行走的方法,武器通过武器类实现


添加武器类


继承:子类拥有父类的所有方法和属性。子类继承自父类,可以直接享受父类中已经封装好的方法,不需要再次开发。子类中应该根据职责,封装子类特有的属性和方法
class 类名(父类名):
pass


重写


多继承:根据就近原则调用父类的方法。




__str__方法:打印/显示实例时调用方法,返回字符串
__call__方法:用于创建可调用的实例


正则表达式及re模块:
\d:匹配任意数字,与[0-9]同义
\s:匹配空白字符
{n}:匹配前面出现的正则表达式至少n次
^:匹配字符串的开始
$:匹配字符串的结尾
\b:匹配单词的边界
():对正则表达式分组
match函数:尝试用正则表达式模式从字符串的开头匹配,如果匹配成功,则返回一个匹配对象;否则返回None。span:索引区间,group函数:获取匹配的值
search函数:在字符串中查找正则表达式模式的第一次出现,如果匹配成功,则返回一个匹配对象;否则返回None
findall函数:在字符串中查找正则表达式模式的所有(非重复)出现;返回一个匹配对象的列表
findall函数:在字符串中查找正则表达式模式的所有(非重复)出现;返回一个匹配对象的列表
finditem函数:和findall()函数有相同的功能,但返回的不是列表而是迭代器;对于每个匹配,该迭代器返回一个匹配对象


split函数:根据正则表达式中的分隔符把字符分割为一个列表,并返回成功匹配的列表。字符串也有类似的方法,但是正则表达式更加灵活
sub函数:把字符串中所有匹配正则表达式的地方替换成新的字符串
compile函数:对正则表达式模式进行编译,返回一个正则表达式对象不是必须要用这种方式,但是在大量匹配的情况下,可以提升效率


练习:分析apache访问日志
统计每个客户端访问apache服务器的次数,将统计信息通过字典的方式显示出来,分别统计客户端是Firefox和MSIE的访问次数
创建日志文件



什么是进程:计算机程序只不过是磁盘中可执行的、二进制(或其它类型)的数据。进程(有时被称为重量级进程)是程序的一次执行。每个进程都有自己的地址空间、内存以及其它记录其运行轨迹的辅助数据。操作系统管理在其上运行的所有进程,并为这些进程公平地分配时间。
什么是线程:线程(有时被称为轻量级进程)跟进程有些相似。不同的是,所有的线程运行在同一个进程中,共享相同的运行环境。一个进程中的各个线程之间共享同一片数据空间,所以线程之间可以比进程之间更方便地共享数据以及相互通讯。
进程是争夺CPU、内存等资源的最小单位,线程是程序执行的最小单位。
多线程工作原理:在多线程(MT)编程出现之前,电脑程序的运行由一个执行序列组成,执行序列按顺序在主机的中央处理器(CPU)中运行。无论是任务本身要求顺序执行还是整个程序是由多个子任务组成,程序都是按这种方式执行的。即使子任务相互独立,互相无关(即,一个子任务的结果不影响其它子任务的结果)时也是这样。如果并行运行这些相互独立的子任务可以大幅度地提升整个任务的效率。它们本质上就是异步的,需要有多个并发事务。各个事务的运行顺序可以是不确定的,随机的,不可预测的这样的编程任务可以被分成多个执行流,每个流都有一个要完成的目标
根据应用的不同,这些子任务可能都要计算出一个中间结果,用于合并得到最后的结果。
threading模块:提供线程类
根据应用的不同,这些子任务可能都要计算出一个中间结果,用于合并得到最后的结果。
threading模块:提供线程类


使用多线程会同时进行该函数


传递参数


练习:编写ping函数
用于测试远程主机的连通性


在Python中使用pip来下载安装模块(相当于Linux的yum)

list:查看所有的模块


安装模块pip3 install 模块名。从公网上下载paramiko模块的软件包

在安装pymysql模块

卸载为pip3 uninstall 模块名
使用国内镜像站点,配置pip.conf文件
在root下创建pip隐藏目录。配置国内镜像源,index-ur1指定国内镜像源路径,trusted-host信任该镜像网站,否则无法使用22222654

