Python函数进阶
默认参数:
wangchao@wangchao-virtual-machine:~/python$vim default.func.py
#!/usr/bin/python
defname_info(name,age,job,nationnality='Chinese'):
print '''%s's information:
Name: %s
Age: %s
Job: %s
Country: %s ''' %(name,name,age,job,nationnality)
name_info('cai',23,'IT','American')
name_info('ru',25,'Engineer')
//无输入,则默认填写Chinese。-----默认参数使用
程序运行结果:
wangchao@wangchao-virtual-machine:~/python$python default.func.py
cai's information:
Name: cai
Age: 23
Job: IT
Country: American
ru's information:
Name: ru
Age: 25
Job: Engineer
Country: Chinese
关键参数:
某一函数有许多参数,而你只想指定其中一部分,则可以通过命名来为这些参数赋值。这被称作关键参数
wangchao@wangchao-virtual-machine:~/python$vim 1.py
#!/usr/bin/python
#Filename:fun_key.py
def func(a,b=5,c=10):
print 'a is',a,'b is', b, 'c is' , c
func(3,7)
func(25,c=24)
func(c=50,a=100)
// func(c=50,a=100)指定某参数为特定值,关键参数
运行结果:
wangchao@wangchao-virtual-machine:~/python$python 1.py
a is 3 b is 7 c is 10
a is 25 b is 5 c is 24
a is 100 b is 5 c is 50
全局变量、局部变量
>>> def lisst(a,b=5,c=10):
... global a
... print "a:%s b:%s c:%s" %(a,b,c)
...
File "<stdin>", line 1
SyntaxError: name 'a' is local and global
//出错,全局变量不能这样设置
>>> def lisst(a,b=5,c=10):
... print "a:%s b:%s c:%s" %(a,b,c)
... return a
...
>>> lisst(c=50,a=100)
a:100 b:5 c:50
100 //return返回a的值
>>> result=lisst(c=50,a=100) //将函数赋值给result
a:100 b:5 c:50
>>> print result //result为函数的返回值returna为100
100
>>> defname_info(name,age,job,nationnality=chinese):
... global ll //定义一个全局变量ll(要在函数内)
... ll='ddd'
... global age //并不能将age定义为全局变量,该函数为在函数外
... return 'success'
... return 'aaa'
// globall定义一个全局变量ll(要在函数内)
//global age并不能将age定义为全局变量,该函数为在函数外(name,age,job,nationality)都不能将其定义为全局变量
//return 'success' return 'aaa' 后一条return 'aaa'并未生效,一个函数只能有一个return值(return退出),要返回两个值,可改为return ‘success’,’aaa’
Pickle序列化
类似于游戏中存档,下次打开时从结束处开始(将内存的数据存入硬盘)
wangchao@wangchao-virtual-machine:~/python$vim acc.py
#/usr/bin/python
account_info={'0001':['cai',1500,1500],
'0002':['ru',3000,3000],
}
wangchao@wangchao-virtual-machine:~/python$python
>>> import acc
>>> acc.account_info //调用字典
{'0001': ['cai', 1500, 1500], '0002':['ru', 3000, 3000]}
>>> acc.account_info['0001'] //取出0001
['cai', 1500, 1500]
>>>acc.account_info['0001'][1] //取出1500
1500
>>>acc.account_info['0001'][1]=5000 //将第一个1500改成5000
>>> acc.account_info
{'0001': ['cai', 5000, 1500], '0002':['ru', 3000, 3000]}
假设现要将其存入文件,退出打开文件后为修改后的5000
>>> f=open('acc.log','w')
>>>f.write(acc.account_info) //写入失败,只能写入字符串,不能将字典写入
Traceback (mostrecent call last):
File "<stdin>", line 1, in<module>
TypeError:expected a character buffer object
>>> '%s' %acc.account_info //将字典变成字符串
"{'0001': ['cai', 5000, 1500], '0002':['ru', 3000, 3000]}"
>>> s='%s' %acc.account_info
>>> f.write(s) //写入
>>> f.close()
wangchao@wangchao-virtual-machine:~/python$more acc.log //查看写入的文件
{'0001': ['cai', 5000, 1500], '0002':['ru', 3000, 3000]}
假设现想把存入的数值取出怎么办,取出则很麻烦,以上为字典存入,与取出的办法非常麻烦。
现使用pickle序列化来完成
Pickle 语法dump
import pickle
account_info={‘1886’:[‘wang’,1500,1500],
‘1887’:[‘cai’,900,900],
}
f=file(‘account.pkl’,’wb’) //打开一文件
pickle.dump(account_info,f) //存入文件
f.close()
wangchao@wangchao-virtual-machine:~/python$vim acc_dumpy.py
#!/usr/bin/env python
import pickle
account_info = {'001':['wang',15000,15000],
'002':['cai',2000,2000],
}
f=open('acc.pkl','w+')
pickle.dump(account_info,f)
f.close
wangchao@wangchao-virtual-machine:~/python$python acc_dumpy.py
wangchao@wangchao-virtual-machine:~/python$more acc.pkl //已产生文件
(dp0
S'002'
p1
(lp2
S'cai'
p3
aI2000
aI2000
asS'001'
p4
(lp5
S'wang'
p6
aI15000
aI15000
as.
现取出文件
wangchao@wangchao-virtual-machine:~/python$vim acc_load.py
#!/usr/bin/python
import pickle
f=open('acc.pkl','r+')
account_info=pickle.load(f)
print account_info
// pickle.load(f)将文件中的字典load进来,并给变量account_info,printaccount_info打印
wangchao@wangchao-virtual-machine:~/python$python acc_load.py //查看打印
{'002': ['cai', 2000, 2000], '001':['wang', 15000, 15000]}
修改内容
wangchao@wangchao-virtual-machine:~/python$vim acc_load.py
#!/usr/bin/python
import pickle
f=open('acc.pkl','r+')
account_info=pickle.load(f)
print account_info
account_info['002'][1]=16000
account_info['002'][2]=16000
print account_info
wangchao@wangchao-virtual-machine:~/python$python acc_load.py //内容已修改
{'002': ['cai', 2000, 2000], '001': ['wang',15000, 15000]}
{'002': ['cai', 16000, 16000], '001':['wang', 15000, 15000]}
//但现在只在内存中,并未存入文件
现把修改后的值存入文件:
wangchao@wangchao-virtual-machine:~/python$vim acc_load.py
#!/usr/bin/python
import pickle
f=open('acc.pkl','r+')
account_info=pickle.load(f)
f.close() //防止出现写入多个字典
account_info['002'][1]=16000
account_info['002'][2]=16000
f=open('acc.pkl','w')
pickle.dump(account_info,f)
f.close()
//每dump一下,都需要从新写一遍,即重新打开文件一次
//查看原先的
wangchao@wangchao-virtual-machine:~/python$python acc_dumpy.py
wangchao@wangchao-virtual-machine:~/python$more acc.pkl
(dp0
S'002'
p1
(lp2
S'cai'
p3
aI2000
aI2000
asS'001'
p4
(lp5
S'wang'
p6
aI15000
aI15000
as.
执行后查看值已修改
wangchao@wangchao-virtual-machine:~/python$python acc_load.py
wangchao@wangchao-virtual-machine:~/python$more acc.pkl
(dp0
S'002'
p1
(lp2
S'cai'
p3
aI16000
aI16000
asS'001'
p4
(lp5
S'wang'
p6
aI15000
aI15000
as.
Pickle语法load
Import pickle
#load data first
pkl_file = open(‘account.pkl’,’rb’)
account_list = pickle.load(pkl_file)
pkl_file.close()
python正则表达式
import re
#将正则表达式编译成pattern对象
pattern = re.compile(r‘hello’)
#使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None
match = pattern.match(‘hello world!’)
if match:
printmatch.group()
###输出###
#hello
例子:
>>> import re
>>> p = re.compile(r'hello')
>>> m = p.match('hello,world')
>>> print m.group()
Hello
>>> p = re.compile(r'he') //匹配he
>>> m = p.match('hello,world')
>>> print m.group()
he
写法2,不写pattern
m = re.match(r’hello’,’hello world!’)
print m.group()
例子:
>>> m = re.match(r'tom','tompam')
>>> print m.group()
tom
>>> m =re.match(r'tom','tompamtom')
>>> print m.group() //匹配的第一个tom
tom
>>> m =re.match(r'tom','tgdettompamtom')
>>> print m.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has noattribute 'group'
//未匹配成功,只匹配开头的
split(string[,maxsplit])|re.split(pattern,string[,maxsplit]):
按照能够匹配的子串string分割后返回列表。Maxsplit用于指定最大分割次数,不指定将全部分割。
import re
p = re.compile(r'\d+')
print p.split(‘one1two2there3four4’)
###output###
#[‘one’,’two’,’there’,’four’,’’]
Findall(string[,pos[,endpos]])|re.findall(pattern,string[,flags]):
搜索string,以列表形式返回全部能匹配的子串。
print p.findall(‘one1two2there3four4’)
>>> p = re.compile(r'\d+')
>>> r =p.split('one1two2there3four4')
>>> print r
['one', 'two', 'there', 'four', '']
>>> p = re.compile(r'\d+')
>>>p.findall('one1two2there3four4five')
['1', '2', '3', '4']
re.sub函数进行以正则表达式为基础的替换工作
>>> re.sub('[abc]','o','Mark')
'Mork'
>>> re.sub('[abc]','o','rock')
'rook'
>>> re.sub('[abc]','o','caps')
'oops'
>>>re.sub('[abc]','o','mastash',1)
'mostash'
创建使用模块
为了实现对程序特定功能的调用和存储,人们将代码封装起来,可以供其他程序调用,可以称之为模块。
使用模块的好处:
程序可扩展性
减少程序代码
方便程序架构的更改
常用模块
import sys
sys.path
sys.argv
sys.exit
import os
os.system(‘uname’)
os.mkdir(‘myDir’)
os.chdir(‘~’)
time
>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:38)\n[GCC 4.8.2]'
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=6,releaselevel='final', serial=0)
>>> sys.maxsize
2147483647
>> sys.exit() //退出
wangchao@wangchao-virtual-machine:~/python$
>>> import tab
>>> import sys
>>> sys.path //查看路径
['', '/usr/lib/python2.7','/usr/lib/python2.7/plat-i386-linux-gnu', '/usr/lib/python2.7/lib-tk','/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload','/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages','/usr/lib/python2.7/dist-packages/PILcompat','/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client']
wangchao@wangchao-virtual-machine:~/python$vim argv.py
#!/usr/bin/python
import sys
print sys.argv[0]
print 'You argumentsare:',sys.argv[1],sys.argv[2]
wangchao@wangchao-virtual-machine:~/python$python argv.py hello world argv.py
You arguments are: hello world
//打印输入的两个参数,传递参数
>>> import tab,os
>>> os.system('df -h')
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 19G 3.5G 15G 20% /
none 4.0K 0 4.0K 0% /sys/fs/cgroup
udev 493M 4.0K 493M 1% /dev
tmpfs 101M 1.4M 100M 2% /run
none 5.0M 0 5.0M 0% /run/lock
none 502M 152K 502M 1% /run/shm
none 100M 44K 100M 1% /run/user
/dev/sr0 1003M 1003M 0 100% /media/wangchao/Ubuntu 14.04.2 LTSi386
0
//命令执行成功返回0.
>>> test = os.system('df -h')
>>> print test //可用于写程序,命令是否执行成功
0
>>> a=os.popen('df')
>>> a.read() //将df结果存入文件,读
'Filesystem 1K-blocks Used Available Use% Mountedon\n/dev/sda1 19478204 3624320 14841404 20% /\nnone 4 0 4 0% /sys/fs/cgroup\nudev 503852 4 503848 1% /dev\ntmpfs 102720 1336 101384 2% /run\nnone 5120 0 5120 0% /run/lock\nnone 513600 152 513448 1% /run/shm\nnone 102400 44 102356 1%/run/user\n/dev/sr0 1027072 1027072 0 100% /media/wangchao/Ubuntu 14.04.2LTS i386\n'
>>>a=os.popen('df')
>>> a.readlines() //列表方式
['Filesystem 1K-blocks Used Available Use% Mounted on\n','/dev/sda1 19478204 3624320 14841404 20% /\n', 'none 4 0 4 0% /sys/fs/cgroup\n', 'udev 503852 4 503848 1% /dev\n', 'tmpfs 102720 1336 101384 2% /run\n', 'none 5120 0 5120 0% /run/lock\n', 'none 513600 152 513448 1% /run/shm\n', 'none 102400 44 102356 1% /run/user\n', '/dev/sr0 1027072 1027072 0 100%/media/wangchao/Ubuntu 14.04.2 LTS i386\n']
>>> a=os.popen('df')
>>> for i in a.readlines():
... print i
...
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda1 19478204 3624320 14841404 20% /
none 4 0 4 0% /sys/fs/cgroup
udev 503852 4 503848 1% /dev
tmpfs 102720 1336 101384 2% /run
none 5120 0 5120 0% /run/lock
none 513600 152 513448 1% /run/shm
none 102400 44 102356 1% /run/user
/dev/sr0 1027072 1027072 0 100% /media/wangchao/Ubuntu 14.04.2LTS i386
>>> os.getcwd() //查看当前目录
'/home/wangchao/python'
>>>os.chdir('/usr/local/src') //切换目录
>>> os.getcwd()
'/usr/local/src'
可以通过os调用linux中任何命令
Time模块
>>> import time
>>> time.sleep(3) //睡眠3秒
>>> time.time() //时间,从1970年到现在的秒数
1439910124.102958
>>> time.strftime('%y')
'15'
>>> time.strftime('%Y')
'2015'
>>> time.strftime('%Y%m%d%H:%M:%S')
'20150818 23:04:50'
>>> time.timezone //时区
-28800
datetime模块
>>> import datetime
>>> datetime.timedelta() //计算日期程序
datetime.timedelta(0)
>>>(datetime.datetime.now()-datetime.timedelta(days=3)).strftime("%Y-%m-%d")
'2015-08-16'
//计算三天前的日期
>>> (datetime.datetime.now()+datetime.timedelta(days=3)).strftime("%Y-%m-%d")
'2015-08-22'
//计算三天后日期
制作模块
#!/usr/bin/python
name=’my first module’
version =’0.1’
youName=raw_input(‘what is your name?’)
print ‘So your name is’,youName
练习程序:
备份脚本
实现常规备份功能
记录日志
备份时可指定排除目录