python基础
pycharm快捷键
ctrl+d 复制行
ctrl+x 删除行
ctrl+/ 注释
''' 多行注释,只能用于模块头部
shift+↑或↓ 选择
shift+alt+↑或↓ 移动行
ctrl+alt+L 美化代码
tab 补全命令
在终端中执行py文件:python3 g:/test.py
r=str.func(argv) #执行func(),并将返回值赋给变量r
假如func中无return,默认return None
内存产生了新的对象就需要return.
例如:list.append()list修改了,故不用return;
'abc'.lower(),字符串本身不能修改,内存中产生了新的区域,故return 结果
1. 变量
name = "liming"
age = 25
print(name, "'age is ", age) #print()用来打印, ,用来连接
name,age="zhangsan",23
2. 常量
全部大写NAME='miling'
MYSQL_CONNECTION=""
3. name = 'Alex'
name2 = name
name = 'longmingwang'
print(name, name2) #longmingwang Alex
4. 在pycharm中文件->设置->editor->文件和代码模版中修改python script中添加#author xinwang
这样所有的新建python文件都会有这行注释
5. 在python2中
input:输入的数字就是数字,"alex"是文本,alex是变量
raw_input:输入全部是文本
在python3中
input:输入的全是文本
6. '''打印多行文本
7. 例子
name = input("please input your name:")
age = int(input("please input your age:"))
job = input("please input your job:")
msg = ('''information of user %s
---------------------------
name : %s
age : %d
job : %s''') % (name, name, age, job)
print(msg)
8. getpass:在pycharm中无效
1 >>> import getpass
2 >>> p=getpass.getpass('input your password')#输入密码时用getpass代替了input
3 input your password
4 >>> print(p)
5 aaa
9. os:在python中执行系统命令
import os
print(os.system("top"))
os.mkdir("/home/wangxin/test)
print(os.system("ls -l /"))
保存命令输出:rs=os.popen("df").read()
print(rs)
10.sys
import sys
print(sys.argv) #参数
print(sys.path)
11. if ... else
模拟登录:
user = 'alex'
passd = 'alex'
username = input("username:")
password = input("password:")
if username == user:
print("the username is correct...")
if password==passd:
print ("welcome to login")
else:
print("but your password is invalid")
else:
print("连用户名都没蒙对,滚粗!")
优化:
if username == user and passd==password:
print("welcome to login")
else:
print("your username or password is invalid!")
age=21
guessnum=int(input("guess age:"))
if age==guessnum :
print("got it! so smart!")
elif guessnum>age:
print("elder than age")
else:
print("smaller than age")
12. for i in 列表:
age=21
for i in range(10): #range(10)=[0,1,2,3,4,5,6,7,8,9]
guessnum=int(input("guess age:"))
if age==guessnum :
print("got it! so smart!")
break #不往后走了,跳出整个循环
elif guessnum>age:
print("elder than age")
else:
print("smaller than age")
13. 程序执行顺序
n = int(input("n="))
if n > 1:
print("n>1")
elif n > 2:
print("n>2")
else:
print("heha")
print("end")
结果:
n=8
n>1
end
14. 字符串格式化输出
name="liming"
print("I am %s" % name)
万恶的+:开辟多个内存空间
print("my name is "+name+"!")
15.列表====数组
age=9
name=["minglong","minghu","mingchong",3,age]
列表名[索引]
print(name[0]) #"minglong"
print(name[-1]) #age
只会从左到右取:
name[0:2] #["minglong","minghu"]
name[-3:-1]
name[:6]#前五个
name[:]全部
name[2:6][2:4][0][1]
赋值
name[1]="newname"
name.insert(2,"minggou")#在2元素前插入
name.append("alex")#在列表最后插入
删除:
name.remove("minggou")#删除找到的第一个为minggou的项
name.pop(7) #不加参数默认为-1
del #删除内存中的数据,全局使用
del student[4:6] #删除第4,5
del student #删除列表
步长:
student[0:8:2]
个数:
student.count("s2")
查找值:
判断是否存在: "s2" in student
student.index("s2")#找到的第一个s2的索引位置
eg:改掉里面所有的s4:
for i in range(student.count('s4')):
i=student.index("s4")
student[i]="444"
清空:
student.clear()
扩展:
student1.extend(student2)
反转:动作,无返回值
student.reverse()
排序:
student.sort()#python3中字符串和数字不能一块排序
复制:
copy:浅层复制
student2=student.copy()
eg:
student = [1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
student2 = student.copy()
student[0] = 54
print(student)
print(student2)
student[4][0]=64365464
print(student)
print(student2)
结果为:
[54, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[54, 2, 3, 4, [64365464, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [64365464, 7, 6, 5], 43, 32, 12]
deepcopy:深层复制
import copy
student2=copy.deepcopy(student)
eg:
import copy
student = [1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
student2 = student.copy()
student3 = copy.deepcopy(student)
student[0] = 54
print(student)
print(student2)
print(student3)
student[4][0]=64365464
print(student)
print(student2)
print(student3)
结果:[54, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
[54, 2, 3, 4, [64365464, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [64365464, 7, 6, 5], 43, 32, 12]
[1, 2, 3, 4, [5, 7, 6, 5], 43, 32, 12]
长度:
len(student)
16.元组:不可修改的list
( )tuple
17.字符串
str.strip() ---删除两边空白-空格,tab
str.split() ---str没变,得到个列表
"|".join(['a','bc','1']) ---将列表中元素(必须都是字符串)用|拼成字符串 :a|bc|1
"".join(['a','b','c'])-->abc
"" in "alex li" ----判断空格
"1234".isdigit() ----判断字符串是否是纯数字组成,True
'fe'.isalpha() ----是不是字母
'feAFE'.isupper() ----是不是全是大写
'fwef'.islower() ----是不是全是小写
ord('c') -->99
chr(99) -->c
格式化:format
msg = "name={0},age={1}"
print(msg.format('liming', 27))
语法
'{0},{1}'.format('kzc',18)
'{name},{age}'.format(age=18,name='kzc')
精度与类型f
{:.2f}'.format(321.33345)
'321.33'
其中.2表示长度为2的精度,f表示float类型。
{1:.2f}'.format(2325,321.33345)
"alex".center(40,"-") #------------------alex------------------
"alex".find("ex") #2,返回所引
print("abcd".endswith("d")) #True
print("abcd".startswith("a")) #True
字符串是列表:
for i in 'abcd':
print(i)
eg:生成六位验证码:
import random
yanzhengma=[]
for i in range(6):
jj=random.randrange(0,2)
if jj==0:#数字
temp=random.randrange(0,10)
yanzhengma.append(str(temp))
else:
temp=random.randrange(65,91)
r=chr(temp)
yanzhengma.append(r)
yanzhengma="".join(yanzhengma)
print(yanzhengma)
' %s,%.2f '%('liming',21)
s:str
r:str
c:ASICCI数字转为字母,%c 当c=65时就是a
o:整数转化为八进制
x:将
18. 数据运算
% -----除法的余数,判断正奇数
// -----商的整数部分
!= -----不等于
== -----等于
赋值:左边一定是变量
= -----赋值
+= -----相加;c+=a-->c=a+c
-=
and
or
not
位运算:计算机中能存储,表示的最小单位,是一个二进制位
byte(字节)=8bit
1kbyte=1024byte
1Mbyte=1024kbyte
1Gbyte=1024Mbyte
1 1 1 0 1 1=60
0 0 1 1 0 1=13
60 & 13 =12 ---按位与运算
60 | 13 =61 ---按位或运算
60 ^ 13=49 ---按位异或
~60=195-256=-61 ---按位取反
64<<1=128 左移1位
64>>1=32 右移1位
19.死循环
while True
i = 0
while True:
i += 1
if i>50 and i<60:
continue
print("i=", i)
if i==100:
print("fuck!!!")
break
20.字典{}:无序
d={key1:value1,key2:value2,key3:value3}
d[key2]=value_2_new
eg:
d = {
"001": {
"name": "liming",
"age": 25,
"address": "henan"},
"002": {
"name": "zhangsan",
"age": 65,
"address": "yongxia"},
"003": {
"name":"lisi",
"age":85,
"address":"jinan"
}
}
d["002"].pop("age") --->删除age:65
print (d["002"]["age"])
取出所有的keys列表
d.keys()
取出所有的values列表
d.values()
判断key是否存在
"003" in d ---->True
循环
for key in d:
print(key)
print(d[key])
取值不抱错: d[]可能会报错
setdefault:存在时就直接取出(相当于get),没有就设置默认值后取出
print(d.setdefault("003",{"name":"sim"}))
get: d.get("003")
删除:
d.pop(key)
d.popitem() -->随机删除
21. 退出程序
exit("sorry")
打印出列表中索引号:
for i in enumerate(range(5)):
print(i)
结果为:
(0, 0)
(1, 1)
(2, 2)
(3, 3)
(4, 4)
22.set集合---无序,不可重复
创建:
s={123,456,789,852,46}
s=set([])#调用了构造函数__init__
添加元素:
add:
s.add(123)
update:列表或元组或字符串;for循环加入
s.update([1,2,3])#一次添加多个元素
s.update("abcdabcd")#新增了'a','b','c','d'
清空:
s.clear()
差异:
s.different(s1)#s中存在,s1中不存在
s1.symmetric_difference(s)#并集中去掉交集
差异更新:
s.different(s1)#求差异更新到s中
s1.symmetric_difference_update(s)
移除:
remove:
s.remove(111)#不存在时会报错
discard:
s.discard(123)#即使不存在也不会报错
pop:
s.pop() #随机删除,不建议使用
交集:
s.intersection(s1)
s.intersection_update(s1)
并集:
s.union(s1)
23.函数,在py文件中可直接定义,不需要一定在class中定义,参数传的是引用
在内存中,函数名----->函数体
默认参数:
def fun1(x,y,z='ok'):
print (x,y,z)
return x+y #终止了函数,没有return时默认是None
print() #不会被执行
调用:fun1(2,3,'ss') #2 3 'ss'
fun1(2,3) #2,3,'ok'
def func1():
return 1,2,3,4 #多个返回值会放进元组
r=func1() r=(1,2,3,4)
参数:传递给形式参数的是引用
动态参数:
*args,将传进来的参数放在一个元祖中
eg:
def ff(*args):
print(args)
ff("nilian","hello","world") #args=('nilian', 'hello', 'world')
ff(("nilian","hello","world")) #args=(('nilian', 'hello', 'world'))
ff(["nilian","hello","world"]) #args=(['nilian', 'hello', 'world'])
循环的放进元祖中:
ff(*"hello") #args=('h', 'e', 'l', 'l', 'o') <class 'tuple'>
ff(*("hello","world")) #args=('hello', 'world') <class 'tuple'>
ff(*["hello","world"]) #args=('hello', 'world') <class 'tuple'>
ff(*[1,2,3],4) #args=(1,2,3,4)
**args:将传进来的参数放在字典中
def ff(**args):
print(args,type(args))
参数:变量=''
ff(name="liming",age=21) #args={'name': 'liming', 'age': 21} <class 'dict'>
参数:**{字典}
ff(**{'name':"liming"}) #args={'name':'liming'} <class 'dict'>
万能参数:
def f(*args,**args):
f(1,2,3,name='zhangsan',age=21)
字符串有个函数:format(*args,**args)
全局变量:大写
任何作用域都能读
重新赋值全局变量,先:声明global 变量名 再:变量名=''
局部变量:只有本函数能访问
优先访问自己的局部变量
在函数中一旦赋值=,就会产生局部变量,当和全局变量重名时,修改不会影响全局变量
school=['qinghua','beida','zhongxi']
def change():
school=['chuanda','beida']#会产生个局部变量,优先使用
school[0]='shangda'
print(school[0])#'shangda'
change()
print(school) #school=['qinghua','beida','zhongxi']
school=['qinghua','beida','zhongxi']
def change():
school[0]='shangda'
print(school[0]) #'shangda'
change()
print(school[0]) # 'shangda'
python是面向函数编程.封装到函数,
内置函数:
abs:绝对值
bool():0,None,False,"",(),[],{}为False
all():全为True,才为True,如all([1,2,None])为假
any():有一个True,就为True,如any([1,2,None])为真
bin():二进制0b
oct():八进制0o
hex():十六进制0x
utf-8:一个汉字三个字节,一个字母一个字节
gbk:一个汉字两个字节,一个字母一个字节
bytes():转化为字节,如bytes('lisa啊',encoding='utf-8')-->b'lisa\xe5\x95\x8a' ,a-z不变,0-9不变,汉字会转化为3个字节,每个字节为两个十六进制
str():str(b'lisa\xe5\x95\x8a',encoding='utf-8')-->'lisa啊' .字节转化为字符串
操作文件
权限:r,(w,a),r+,w+,a+
打开文件:f=open('db','r',[encoding='utf-8']) #只读,读的是字符串,乱码时要写对encoding
f=open('db','rb') #以二进制读取,
f=open('db','w') #只写,先清空
f=open('db','wb') #以二进制写入,f.write(bytes('lisa',encoding='utf-8'))
f=open('db','x') #文件存在则报错,不存在,则创建并写内容
f=open('db','a') #追加,可读,不存在则创建,存在则只追加内容
+:可以同时读写
f.seek(1) #按字节调整读指针,跳过一个字节,有汉字(三个字节)会乱码)
f.tell() #获取现在指针位置,一个汉字为三个字节
f=open('db','r+') #读写,可读可写,因为读导致指针移到最后了,所以write在末尾(追加)
f=open('db','w+') #写读,可读可写
f=open('db','x+') #写读,可读可写
f=open('db','a+') #写读,可读可写
eg:
f=open('db','r+',encoding='utf-8')
r=f.read(1) #汉字
print(r)
p=f.tell() #3
f.seek(p)
f.write('lisi|35252')
f.close()
操作文件:
f.read():读取,指针随着移动,无参数读全部,有参数时看打开方式:
r:按字符读,
rb:按字节读
write():写入,wb时写入字节
flush():将修改flush到磁盘
readable():w模式打开时False
readline():读取一行,指针随着一行
readlines():每一行都作为一个元素放到list中,读取所有行到内存,不推荐
truncate():截断文件,指针后清空
for line in f:一行一行的读取文件
关闭文件:f.close()
with open('db','r') as f,open('db1','r') as f2:
pass
compile:将字符串编译成python代码,eval,exec来执行代码
s="print(4)"
r=compile(s,'<string>','exec')
exec(r)
exec:执行python代码,没有返回值,接收代码或字符串
exec("print(23)")--->23
eval:执行表达式运算,并返回值
eval("print(23)")--->23,并返回None
eval('8*8') ---->返回64
dir:查看对象提供了什么功能
divmod:返回元组(商,余数)
isinstance:判断对象是不是类的实例
l=[]
r=isinstance(l,dict)
print(r) -->False
类:str,dict,list
str的实例:"alex"
dict的实例:{}
list的实例:[]
lambda:只有一个表达式,即: 表达式(返回值)
def add(x,y):
return x+y
等价于:
add=lambda x,y:x+y
filter:筛选器,filter(f,list)
第一个参数:函数f(x),返回True,False
第二个参数:[],{}
li=[11,22,3,44,55]
r=filter(lambda a:a>22,li)
print(list(r))
map:map(f,list)
第一个参数:函数f(x),有一个返回值
第二个参数:[],{}
li=[11,22,3,44,55]
r=map(lambda a:a+100,li)
print(list(r))
reduce:reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:
>>> from functools import reduce
>>> reduce(lambda x,y:x+y, [1, 3, 5, 7, 9])
25
globals() #全局变量
locals() #局部变量
hash():生成哈希值,主要是dict中的key
len():字符长度,求字节长度:len(bytes(" ",encoding='utf-8'))
zip:-->:列表拼接
zip(['zhangsan','lisi'],[21,34])
print(list(r))---->[('zhangsan', 21), ('lisi', 34)]
25. input的列表或者字典文本转化为list,{}
import json
s='["1",2,3,4]' #文本,里面只能使用""
print(s,type(s))
r=json.loads(s) #将一个字符串转换成python的基础数据类型,[],{},注意:字符串形式的字典或者列表内部一定是""
print(r,type(r))
26.返回函数 --->延迟执行
# 请编写一个函数calc_prod(lst),它接收一个list,返回一个函数,返回函数可以计算参数的乘积。
from functools import reduce
def calc_prod(lst):
def cj():
return reduce(lambda x, y: x * y, lst)
return cj
l = [2, 3, 4, 5]
f = calc_prod(l)
r = f()
print(r)
27.装饰器
>函数f可以作为参数,f()是执行f
def f1():
print(12)
def f2(func):
func()
f2(f1)
---->12
>@函数名,某个函数上面
eg:
1 def outer(func):
3 def inner(*args,**kwargs):
6 before
7 r=func(*args,**kwargs)
9 after
10 return r
4 return inner
2 @outer #将装饰器的return赋值给f1,相当于f1=outer(f1)即f1=inner
8 def f1()
print('hello')
return True
5 f1()
功能:自动执行outer(f1),并将执行的返回值重新赋值给f1
28.模块
py:模块
其他:类库
.py文件或者是文件夹
导入:from导入缺点:函数重名是混乱
.py文件:
import math:使用时math.sqrt
from math import sqrt as s:使用时直接sqrt
文件夹中:
import day4.test
from day4.test.func
导入位置:
import sys
sys.path
安装方式:
pip3:相当于yum,apt-get;pip需要先安装,sudo apt-get install python3-pip3,pip3 install requests
源码安装:wget,python setup.py install
升级:pip install --upgrade pymongo
查看已安装模块:pip list|grep pymongo
29.time,datetime
时间的三种格式:
strptime
------------------------------------->
gmtime,localtime
格式化的字符串 时间戳(秒) ---------->tuple(struct_time)
<------------ <------------
ctime time() mktime
<--------------------------------------
strftime
import time
import datetime
print(time.time()) #从1970-01-01到现在的秒数1489369048.7405934
print(time.ctime())#显示时间,Mon Mar 13 09:38:38 2017;参数可为秒数
print(time.gmtime())#time.struct_time(tm_year=2017, tm_mon=3, tm_mday=13,tm_hour=1,...
print(time.localtime())#time.struct_time(tm_year=2017, tm_mon=3, tm_mday=13, tm_hour=9,...;参数可为秒
time.sleep(1)#延迟执行
print(time.mktime(time.strptime('2017-01-01','%Y-%m-%d')) #秒
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))#2017-03-13 09:42:34,t_truple--->str
print(time.strptime('2017-06-01','%Y-%m-%d'))#time.struct_time(tm_year=2017, tm_mon=6, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=152, tm_isdst=-1) str---->t.truple
print(datetime.date.today())#2017-03-13
print(datetime.datetime.now())#2017-03-13 09:44:55.937171
print(datetime.date.fromtimestamp(time.time()))#参数为秒,2017-03-13
print(datetime.datetime.now().timetuple())#time.struct_time(tm_year=2017, tm_mon=3, tm_mday=13, tm_hour=9, tm_min=46, tm_sec=59, tm_wday=0, tm_yday=72, tm_isdst=-1)
print(datetime.datetime.now()+datetime.timedelta(days=10))#2017-03-23 09:48:25.465156
print(datetime.datetime.now()+datetime.timedelta(days=-10))#2017-03-03 09:48:25.465156
30.json,pickle 序列化
使用双引号
dumps(list)
class list----------------->class bytes
<-----------------
loads(bytes)
dump(list,open('wb'))
class list------------------->文件
<-------------------
load(open('rb'))
import json #更加适合跨语言,字符串,基本数据类型
import pickle #仅适用于python,所有类型的序列化
json.dumps(["1","2",3])#列表变成文本
json.loads('["1","2","3"]')#文本变成列表
json.dump([1,2,3],open('db','w'))#变成文本写入'db'文件中
r=json.load(open('db','r'))#从'db'文件中读取文件变成列表
31. logging
CRITICAL > ERROR > WARNING > INFO > DEBUG
import logging
#定义log文件和日志格式
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%m-%d-%Y %H:%M:%S %p',
filename='myapp.log',
filemode='w')
basicConfig方法用于快速设置日志,有下面的参数:
filename 包日志保存到哪个文件
filemode记录日志的模式,a代表在文件中追加日志,w是删除原有文件,创建新文件。
format 设置日志IDE输出格式,
%(levelno)s: 打印日志级别的数值
%(levelname)s: 打印日志级别名称
%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s: 打印当前执行程序名
%(funcName)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号-----(重要)
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程ID
%(threadName)s: 打印线程名称
%(process)d: 打印进程ID--------(重要)
%(message)s: 打印日志信息
%(module)s:模块-------------(重要)
level 日志的严重程度,logging.WARNING
datefmt 日期格式,time.strftime()
stream 日志输出到那里,如果有filename参数,忽略改参数
logging.info("this is the info")
logging.debug("this is the debug")
logging.warning("this is the warning")
logging中包含了四个主要的类:
logger 提供应用程序直接使用的接口
handler将日志记录到指定的输出,例如文件或终端
filter提供了对日志进行过滤的功能
formatter决定日志记录的最终输出格式。
log同时输出到屏幕和文件:
logger=logging.getLogger("test-log")#create a logger
logger.setLevel(logging.DEBUG)#get a global log level
# create console handler and set level to debug
ch=logging.StreamHandler()#print log on the monitor
ch.setLevel(logging.DEBUG)#set the monitor log level
#create the file handle and set level to warning
fh=logging.FileHandler("access.log")
fh.setLevel(logging.WARNING)
#set the format of log
format=logging.Formatter('%(levelname)s[%(asctime)s]%(message)s')
format_for_file=logging.Formatter('%(levelname)s[%(asctime)s]%(message)s')
ch.setFormatter(format)
fh.setFormatter(format_for_file)
#tell the logger to input the log into the specified handler
logger.addHandler(ch)
logger.addHandler(fh)
logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
32.正则表达式
元字符:. ? + * ^ $ {} [] |---在[]中元字符失去效用.但是-^要转义
转义:
\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: 匹配字符边界
match() 决定 RE 是否在字符串刚开始的位置匹配,返回MatchObject
import re
origin='has fdggdg456854125'
r=re.match(r'h(\w+)',origin)
print(r,type(r))#<_sre.SRE_Match object>
origin='has fdggdg456854125'
r1=re.match(r'h(?P<name>\w+)',origin)
print(r1.groupdict())#{'name': 'as'}
search() 扫描字符串,找到第一个 RE 匹配的字符串.返回MatchObject
findall() 找到 RE 匹配的所有子串,并把它们作为一个列表返回,如果有组,则只返回组中匹配
r2=re.findall(r'h(\w+)','has ewgwegwr')#['as']
print(r2)
a = 'one11two222three3333four4444'
ret = re.findall(r'(\d+)',a) #['11', '222', '3333', '4444']
finditer() 找到 RE 匹配的所有子串,并把它们作为一个迭代器返回
`MatchObject` :
方法/属性 作用
string 匹配对象
re 匹配模式
group() 返回被 RE 匹配的字符串
start() 返回匹配开始的位置
end() 返回匹配结束的位置
span() 返回一个元组包含匹配 (开始,结束) 的位置
pattern=re.compile('bc')
r=pattern.match('agehgbcgegw')
r=re.findall(r'(bc)d(fg)','abcdfgfewbcdfgfwgw') #[('bc', 'fg'), ('bc', 'fg')]
r=re.split(r':','abda:fewf:ewg')#['abda', 'fewf', 'ewg']
r=re.sub(r':',',','abda:fewf:ewg')#替换为abda,fewf,ewg
分组:在已经匹配的结果里再匹配
33.try except异常
try:
try_suite
except exception1 as e:
suite_exception1
except (exception2,exception3) as e:
suite_exception..
except : #捕获所有异常
suite
else: #只能有一个
else_suite #没有异常发生时,才执行
finally:
finally_suite #无论异常是否发生,finally字句都会执行.用于关闭文件或者是断开服务器
没有符合的except分句时,异常会向上传递到程序中的之前进入的try中或是到进程的顶端
raise: raise IOError(""):自定义异常
def cross(l1,l2):
if not l1 or not l2:
raise ValueError("sequence must be not-empty")
return [(x,y) for x in l1 for y in l2]
l1=[1,2,3]
l2=[]
r=cross(l1,l2) #报错ValueError: sequence must be not-empty
print(r)
assert:断言 ,assert condition,expression
当not condition时,触发异常
assert 判断 #如果判断不为真,则不进行之后的操作
34. 网络通信socket
tcp服务端:socket()->bind()->listen()->accpet()----------->read(收到请求)--->write(处理应答请求)------------------------->read(关闭请求)---->close()
tcp客户端:socket()->connect()----<连接建立>--->write(请求)----------------------------------->read(得到应答)--->close()
encode decode
str------------>send(bytes)-------->recv(bytes)------------>str
服务端:只能同时服务一个
创建socket对象:tcpconn=socket.socket(family,type)
family:
socket.AF_INET
type:
SOCK_STREAM:TCP
SOCK_DGRAM:UDP
bind:绑定地址,元组(ip,port)
tcpconn.bind(('127.0.0.1',5000))
listen:监听
tcpconn.listen(5)
循环监听状态:使用套接字对象的accept对象接受用户请求
while True:
cli,addr=tcpconn.accept()#cli为连接实例,进入阻塞
print('ok,%s connected' % addr[0])
data=cli.recv(1024) #阻塞状态,客户端不发送数据,会阻塞在此处.客户端断开,会进入死循环(linux,windows中会服务器端也断开).最好加入if data判断
print(data.decode())
cli.send(data)
客户端:
创建socket对象:client_sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
连接至服务器:client_sock.connect(('127.0.0.1',5000))
发送请求:client_sock.send(b'this is the first send')
接受请求:data=tcpclient.recv(1024)
print(data.decode())
模拟ssh:
server:
import socket
import os
server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1',5000))
server.listen(5)
n=1
while True:
ip,addr=server.accept()
while True:
data=ip.recv(1024)#建议最大8192
if data:
print(n)
n+=1
print('recv is ',data.decode())
msg=os.popen(data.decode()).read()
if not msg:
msg='sorry,no output!!!'
ip.send(msg.encode('utf-8'))
#print('resend is ok')
else:
print('the connection is lost')
break
server.close()
client:
import socket
import time
cli=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
cli.connect(('127.0.0.1',5000))
while True:
msg=input('>:')
cli.send(msg.encode('utf-8'))
#print('send is ok')
data=cli.recv(1024)
print('recv is ',data.decode())
35.os sys
import os
import sys
os.system('pwd')-----直接执行命令,并打印出来,不能保存
r=os.popen('pwd').read()------将执行结果read给r
sys.argv 全部参数(包括文件名)放入argv这个列表
sys.argv[0] 执行文件名
如果要使用文件名,需要加上目录或者切换到该目录
import shutil
shutil.copyfile(r.)
print(os.getcwd()) #get current working direcotry
os.stat(目录) #该目录的权限属性等
os.chdir(r'c:\users\')==os.chdir('c:\\users\\')
print(os.listdir('/home/wangxin')) #list the directory in []
os.remove('/home/wangxin/test.txt') #remove file
shutil.rmtree('dir')#remove a dir
os.sep #linux为/,windows为\
os.rmdir('/wangxin/text') #remove a empty direcotry
os.removedirs() #递归remove empty dirs直到不为空
os.mkdir('/wangxin/text') #make a direcotory
os.makedirs('/wangxin/test/') #递归建立目录
print(os.path.abspath('.'))#get current working directory
print(os.path.isfile('/home/wangxin/')) #judge a path exists and is a file or not
print(os.path.isdir('/home/wangxin/')) #judge a path exists and is a dir or not
print(os.path.isabs('home/wangxin/')) #judge a path exists and is abspath or not
print(os.path.exists('/home/wangxin')) #judge a path/file is really exists or not
print(os.path.split('/home/wangxin/text.txt')) #('/home/wangxin', 'text.txt') return dir and file from a path
print(os.path.splitext('/home/wangxin/text.txt'))#('/home/wangxin/text', '.txt') 返回扩展名
print(os.path.dirname('/home/wangxin/text.txt')) #return /home/wangxin the dir
print(os.path.basename('/home/wangxin/text.txt')) #return text.txt the filename
os.path.getatime(文件或目录) #ctime or mtime 时间属性
os.system('pwd') #运行shell命令
print(os.environ) #get the env环境变量
print(os.linesep)
os.rename('/home/wangxin/text.txt','/home/wangxin/text_cp.txt')
print(os.stat('/home/wangxin/hello.class')) #返回文件属性
os.chmod('/home/wangxin/hello.java',777)
os.exit()#终止当前进程
print(os.path.getsize('/home/wangxin/hello.java'))
os.mknod('/home/wangxin/testos.txt') #create a new file
shutil.copyfile('oldfile','newfile') #都只能是文件
shutil.copy('oldfile','newfile/dir')#oldfile只能是文件夹,newfile可以是文件或者是目标目录
shutil.copytree('olddir','newdir') #copy the dir
os.chdir("path") # change working dir
36.反射-----通过变量导入模块,函数;适用于快速切换模块
module='os'
func='path'
m=__import__(module)
f=getattr(m,func)
print(f)
def bulk(self):
print('yelling')
class Dog:
def __init__(self,name) :
self.name=name
self.name=name
def eat(self,food):
print('%s is eating %s'%(self.name,food))
d=Dog('lili')
choice=input('>')
for i in range(3):
choice=input('>')
if not hasattr(d,choice):
setattr(d,choice,bulk)
f=getattr(d,choice)
f()
从tcp的package导入bb.py:
1. import importlib
m=importlib.import_module("tcp.bb")
print(m) #<module 'tcp.bb' from ..>
2. m=__import__('tcp.bb')
print(m) #<module 'tcp' from ..>
37.class
class province:
'''this class is going to define a province'''
#static argv,类的属性
n=0
def __init__(self,name,capital):
#动态参数,对象的属性
self.name=name
self.captical=capital
province.n+=1
@staticmethod #申明为静态方法,类的方法,不需要self,不属于类,不能访问类里的任何属性和方法
def sports_meeting():
print(self.name,'on the meeting')
def sports_meeting2(self):
print(self.name,'is on the meeting')
@property #方法变成静态属性
def flag(self):
return __flag
@flag.setter
def flag(self,flag):
self.__flag=flag
def __call__(self, *args, **kwargs):#使对象变成可call
print('this is the __call__')
def __str__(self):
return 'this is the __str__'
sichuan=province('sichuan','chengdu')# 相当于__init__(sichuan,'sichuan','chengdu'),sichuan.name='sichuan',sichuan.captical='chengdu'
shandong=province('shandong','jinan')
print(sichuan.name)
print(shandong.name)
#访问静态方法
province.sports_meeting()
#访问一般方法:
sichuan.sports_meeting()
sichuan.flag #返回__flag
sichuan.flag=5
province.__doc__可以查看到'''this class is going to define a province'''
print(sichuan.__dict__)实例的所有成员,不包含类属性
print(province.__dict__)类的所有成员
print(province.n,sichuan.n,shandong.n) #2,2,2,对象中没有n,访问的是类的n
sichuan.n=9 #sichuan创建了实例变量n
print(province.n,sichuan.n,shandong.n) #2,9,2
sichuan() #相当于调用__call__
print(d) #this is the __str__
class D(A):
def __init__(self,n):
super(D,self).__init__()
def fun(self):
super(D,self).fun()
38.generate 生成器
列表是直接全部产生在内存中
生成器是一种声明,不占内存,遍历时才生成相应的数据,只记录当前的位置,况且要顺序访问,只有__next__方法
简单的生成器:
g=(i for i in range(9) if i%2==0) #g就是generate
复杂的生成器:
生成[1,1,2,3,5,8,13,21,34,55,89,144]
def fi():
a=1
b=1
while n>0:
r=b
b=a+b
a=r
yield b
n-=1
g=fi(10)
for i in g:
print(i)
yield保存生成器状态,中断,next时会从上次field运行到下次yield
39.module
.py的python文件,里面有函数,变量,类等实现一个功能,
import module_name-->module_name.py-->module_name路径(sys.path<包含当前目录>)
使用:同一路径下
from module_name import fun #相当于fun所有源码摘取复制过来,函数可直接调用(慎用,会有冲突)
from module_name import fun as f #别名
import module_name,module_name2 #相当于module_name=编译(module_name),调用时module_name.fun
使用:不同路径下
要将.py文件所在的目录加入到sys.path
例如查找上级目录:
p=os.path.dirname(os.path.abspath(__file__)) #当前文件所在的绝对路径
pp=os.path.dirname(p)#当前目录的父目录
sys.path.insert(1,pp)#插入该父目录
package---包,从逻辑上组织模块
本质是一个目录(必须带有__init__文件)
导入包的本质就是执行该包下的__init__.py文件
导入包:package_name
在__init__.py中:
from . import test
调用时:import package_name
package_name.test.f()
40.random
random.randint(1,5) #[1,5]整数
random.randrange(1,5)# [1,4]整数
random.choice('fwgerew'))#从序列中随机选择一个
random.random()#0-1的浮点数
random.uniform(1,10)浮点数
41.bytes--------------->str(unicode)----------------->bytes
decode encode
s='abc你好'.encode('gb2312') #s=b'abc\xc4\xe3\xba\xc3
ss=s.decode('gb2312')#abc你好
b'abcd1234'='abcd'.encode('utf-8')#b是字节标记,只有[0-9a-z]可以使用
utf-8:
1K=1024bytes [a-z0-9]=1byte 好=3bytes
gb2312:
1k=1024bytes [a-z0-9]=1byte 好=2bytes
42.md5加密
import hashlib
m=hashlib.md5()
m.update(b'hello')
print(m.hexdigest())
m.update(b'world')
print(m.hexdigest()) #helloworld的hash值
43. paramiko sshclient
安装:pip3 install paramiko
import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())#首次连接时
ssh.connect('192.168.67.133',port=22,username='wangxin',password='wangxin')
while True:
cmd=input('>')
if cmd=='exit':break
if not cmd:continue
stdin,stdout,stderr=ssh.exec_command(cmd)
print(stdout.read().decode())
ssh.close()
ssh首次连接服务器时,会在/home中生成隐藏文件.ssh/known_hosts密钥文件
44.scp
scp cputest.py wangxin@192.168.67.128:/tmp
scp wangxin@192.168.67.128:/tmp/cputest.py ./cpu.py
45. 进程process
进程:以一个整体的形式暴露给操作系统管理,一个程序的执行实例(所需资源),唯一的PID,至少一个线程.克隆出子进程,相互独立.进程之间通信需要代理,进程只能操作子进程.进程本身不能执行,只是一个对各种资源管理的集合.
线程:操作系统的最小调度单位,是一串指令的集合.在进程中,是进程的实际运作单位,多个线程执行不同的任务.同一进程里的线程共享同一块内存空间(进程).同一进程的线程通信很简单.可以控制和操作同一进程的其他线程.
进程要操作cpu,必须要先创建一个主线程,主线程创建其他线程.
import threading
import time
def run(name):
print('%s is running' % name)
time.sleep(2)
starttime=time.time()
t1=threading.Thread(target=run,args=('liming',))
t2=threading.Thread(target=run,args=('zhangsan',))
t1.start()#启动t1线程
t2.start()#启动t2线程
t1.join()#阻塞主线程,并行变成串行
print(time.time()-starttime)
class MyThread(threading.Thread):
def __init__(self, username, password, hostname, cmd, port=22):
super(MyThread, self).__init__()
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(hostname=hostname, username=username, password=password, port=port)
self.cmd = cmd
def run(self):
stdin, stdout, stderr = self.ssh.exec_command(self.cmd)
print(stdout.read().decode())
cmd = input('>')
t1 = MyThread('wangxin', 'wangxin', '192.168.67.128', cmd, 22)
t2 = MyThread('wangxin', 'wangxin', '192.168.67.133', cmd, 22)
t1.start()
t2.start()
1.守护线程:不重要的线程,非守护线程结束后就退出了,仆人,殉葬
t.setDaemon(True)
2.event信号量
python线程的事件用于主线程控制其他线程的执行,事件主要提供了三个方法wait、clear、set
全局定义了一个“Flag”,如果“Flag”值为 False,那么当程序执行 event.wait 方法时就会阻塞,如果“Flag”值为True,那么event.wait 方法时便不再阻塞。
signal=threading.Event()
signal.clear():将“Flag”设置为False,此时signal.isSet()为False
signal.set():将“Flag”设置为True,此时signal.isSet()为True
import threading
import time
class MyThread(threading.Thread):
def __init__(self,i,signal):
super(MyThread, self).__init__()
self.name = 'thread-%s' % i
self.signal=signal
def run(self):
print('I am %s,I will sleep...'% self.name)
self.signal.wait()
print('I am thread-%s,I awake'% self.name)
signal=threading.Event()
for i in range(3):
t = MyThread(i,signal)
t.start()
time.sleep(4)
signal.set()
3.queue
class queue.Queue()先进先出
class queue.LifoQueue()后进先出 last in first out
class queue.PriorityQueue()设置优先级
import queue
q=queue.Queue()
q.put('a')
q.put('b')
q.qsize() #2
q.get() #a
q.qsize() #1
q.get() #b
q.get() #一直在等待
q.get_nowait() #a
q.get_nowait() #b
q.get_nowait() #中断返回,queue.empty
q.get(block=False) #a
q.get(block=False) #b
q.get(block=False) #中断返回,queue.empty
q.get(timeout=2) #等待2秒后,中断返回queue.empty
q=queue.PriorityQueue() #设置优先级,get()会先取出优先级大的
q.put((9,'liuneng'))
q.put((6,'zhaosi'))
4.lock
import threading
import time
def run():
global num
time.sleep(1)
lock.acquire()
num-=1
print "num=%d"%num
lock.release()
lock=threading.Lock()
num=100
thread_list=[]
for i in range(100):
t=threading.Thread(target=run)
t.start()
thread_list.append(t)
for i in thread_list:
i.join()
print 'the finally num is %d'%num

浙公网安备 33010602011771号