1 需求 学习Python 2 版本 系统版本:红帽6 内核版本:2.6.32-642.el6 软件版本:Python2.7 3 软件安装 3.1在Python软件安装之前为
1 需求
学习Python
2 版本
系统版本:红帽6
内核版本:2.6.32-642.el6
软件版本:Python2.7
3 软件安装
3.1 在Python软件安装之前为了解决后面的依赖关系,先提前安装一下软件:
zlib zlib-devel
readline-devel
openssl
openssl-devel
[root@wzlvm ~]# yum install zlib zlib-devel readline-devel openssl openssl-devel
3.2 Python安装
下载Python2.7 的源码包,按照源码安装的步骤进行安装
[root@wzlvm python]# lltotal 17604-rw-r--r-- 1 root root 445199 Oct 27 19:31 pip-1.4.1.tar.gz-rw-r--r-- 1 root root 16935960 Oct 27 19:31 Python-2.7.12.tgz-rw-r--r-- 1 root root 639967 Oct 27 19:31 setuptools-27.3.0.tar.gz先解压 Python2.7 的压缩包[root@wzlvm python]# tar -xvf Python-2.7.12.tgz再进入解压目录[root@wzlvm Python-2.7.12]# lltotal 992-rw-r--r-- 1 1000 1000 8466 Jun 26 05:49 aclocal.m4-rwxr-xr-x 1 1000 1000 42856 Jun 26 05:49 config.guess-rwxr-xr-x 1 1000 1000 35740 Jun 26 05:49 config.sub-rwxr-xr-x 1 1000 1000 438205 Jun 26 05:49 configure-rw-r--r-- 1 1000 1000 139347 Jun 26 05:49 configure.acdrwxrwxr-x 22 1000 1000 4096 Jun 26 05:49 Demodrwxrwxr-x 18 1000 1000 4096 Jun 26 05:55 Docdrwxrwxr-x 2 1000 1000 4096 Jun 26 05:49 Grammardrwxrwxr-x 2 1000 1000 4096 Jun 26 05:49 Include-rwxr-xr-x 1 1000 1000 7122 Jun 26 05:49 install-shdrwxrwxr-x 47 1000 1000 12288 Jun 26 05:49 Lib-rw-r--r-- 1 1000 1000 12767 Jun 26 05:49 LICENSEdrwxrwxr-x 11 1000 1000 4096 Jun 26 05:49 Mac-rw-r--r-- 1 1000 1000 48428 Jun 26 05:49 Makefile.pre.indrwxrwxr-x 4 1000 1000 4096 Jun 26 05:49 Miscdrwxrwxr-x 9 1000 1000 4096 Jun 26 05:49 Modulesdrwxrwxr-x 3 1000 1000 4096 Jun 26 05:49 Objectsdrwxrwxr-x 2 1000 1000 4096 Jun 26 05:49 Parserdrwxrwxr-x 9 1000 1000 4096 Jun 26 05:49 PCdrwxrwxr-x 2 1000 1000 4096 Jun 26 05:49 PCbuild-rw-r--r-- 1 1000 1000 35147 Jun 26 05:49 pyconfig.h.indrwxrwxr-x 2 1000 1000 4096 Jun 26 05:49 Python-rw-r--r-- 1 1000 1000 55299 Jun 26 05:49 READMEdrwxrwxr-x 5 1000 1000 4096 Jun 26 05:49 RISCOS-rw-r--r-- 1 1000 1000 98844 Jun 26 05:49 setup.pydrwxrwxr-x 22 1000 1000 4096 Jun 26 05:49 Tools源码安装的第一步,./config 进行校验并制定安装路径[root@wzlvm Python-2.7.12]# ./configure --prefix=/data/program/python2.7接着进行编译安装[root@wzlvm Python-2.7.12]# make && make install
Python2.7 安装完成之后由于以后每次都会用到Python,需要输入Python路径太长,可以做一个软连接
[root@wzlvm Python-2.7.12]# ln -s /data/program/python2.7/bin/python2.7 /usr/bin/python2.7
验证Python是否已经安装成功,进入Python
[root@wzlvm Python-2.7.12]# python2.7Python 2.7.12 (default, Oct 27 2016, 19:37:53) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> a=123>>> a123>>>
Python2.7 已经安装成功
3.3 安装Python工具setuptools
同样的按照源码安装步骤解压安装包setuptools
[root@wzlvm setuptools-27.3.0]# tar -xvf setuptools-27.3.0.tar.gz
解压完成后用Python安装
[root@wzlvm setuptools-27.3.0]# python2.7 setup.py install
注意:这里的setup.py 是用Python运行的安装脚本,每一个源码包里面都有setup.py,这个setup.py 和setuptools 没有直接联系。
3.4 安装pip
pip的安装需要使用上面3.3中安装成功的setuptools ,名叫easy_install,在后台Python安装的路径相同的路径下面
同样的道理,这里easy_install 路径也很长,可以做一个软连接
ln -s /data/program/python2.7/bin/easy_install /usr/bin/easy_install
再用源码安装pip
[root@wzlvm pip-1.4.1]# tar -xvf pip-1.4.1.tar.gz
[root@wzlvm pip-1.4.1]# python2.7 setup.py install
3.5 安装Python开发工具
安装ipython 或者bpython
[root@wzlvm pip-1.4.1]# /data/program/python2.7/bin/pip install ipython
3.6 pip像之前的yum安装一样,也可以配置安装源
在~/.pip/pip.conf 里面配置一下内容(当前配置的是阿里云的pip源)
[global]
timeout=40
index-url= http://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com
4 Python基本语法介绍
常用内置函数:
type():显示数据类型type(123) type('123')
id():显示内存位置 id(a)
dir():显示模块下的所有函数 dir(__builtin__)查看系统所有可用内置的函数
help():显示函数的具体用法 help(platform.uname)
len():显示非数字的字符的长度 len('hello')
len() 可算列表,元组,字典的长度:
>>> len([1,2,3])3>>> len((1,2,3))3>>> len({'n1':1,'n2':2})2
max()取最大值的函数
max() 里面可以比较序列,列表,元组,字典:
>>> max(1,2,3,9,0)9>>> max([1,2,3])3>>> max((1,2,3))3>>> max({'name1':1,'name2':2})'name2'
min()取最小的函数
sum()求和
sum() 可以求列表,元组的和
>>> sum([1,2])3>>> sum((1,2,3))6
转换函数
int() 转换为整型
str() 转换为字符串型
list() 转换为列表
tuple() 转换为元组
dict() 转换为字典
chr() 依照ascii码规则将数字转为字符
ord() 依照ascii码规则将字符转为数字
hex() 10->16进制转换
bin() 10->2进制转换
oct() 10->8进制转换
序列:
列表list:
定义a=[1,2,3,4]
索引a[0],a[2]
切片a[0:4]从第一个元素开始到第四个元素
a[-1]
a[-1::-1]
列表下方法(函数):
a.append()在列表的最后加上以一个元素
a.insert(index,value)在列表中index索引处的前面加入value
a.pop()默认弹出列表的最后一个元素
a.pop(index)弹出列表的index索引处的元素
a.count(value)统计列表中出现value的次数
a.sort()给列表排序默认升序
a.sort(reverse=True)给列表降序排序
a.reverse()给列表降序排序
元组tuple
定义:a=(1,2,3,4)
索引:a[0]
切片:a[0:4] a[-1::-1]
元组下的方法(函数)
a.count(value)统计列表中出现value的次数
字典dict
定义:
a={'key1':value1,'key2':vaule2}
输出:
a['key1'] a['key2']
注意:key的值不要重复不然会造成字典的数据丢失
字符串操作:
a='hello'
大小写转换:
a.lower()把字符串中所有字符都变成小写
a.upper()把字符串中所有字符都变成大写
判断字符组成:
a.isalpha()判断字符串是否全部是由字符构成的
a.isdigit()判断字符串是否全部是由数字构成的
判断某字符在字符串中的索引位置
a.index('h')
判断某字符在字符串中的出现次数
a.count('l')
判断字符串是由那个字符开始或结尾的
a.startswith('h')
a.endswith('o')
替换字符串中的内容
a.replace('h','H')默认全部替换
a.replace('l','L',1)只替换一次满足替换需求的字符
字符串链接
','.join(a)把字符串以,链接起来h,e,l,l,o
'xxx'.join(a)把字符串以xxx链接起来hxxxexxxlxxxlxxxo
字符串分割
a = 'hello this is my python'
a.split() [hello this is my python]形成一个列表默认以空格分割
a.split(',')指定字符串以逗号分割
表达式操作符:
a*b
a+b
a-b
a/b
a%b
逻辑运算符
a and b
a or b
not a
not b
返回布尔值
成员运算符
1 in [1,2,3,4]
1 not in [1,2,3,4]
返回布尔值
比较运算符
a>b
a<b
a>=b
a<=b
a==b
a!=b
位运算符
a|b
a&b
a^b
a<<b
a>>b
幂运算
a**b
索引切片
a[i]
a[1:]
a[-1]
a[-1::-1]
赋值:
a=string
a='hello'
a="hello"
a="""
hello
ok
"""
a=int
a=[]
a=()
a={}
循环控制:
while 条件:
代码块
break跳出当前循环体
continue跳出本次循环进入下次循环
pass占位符
for 变量 in obj:
代码块
if bool_value:
代码块
elif bool_value:
代码块
else:
代码块
bool_value:
真:1,True,非空的变量(有元素的列表,元组,字典,字符),特殊说明:a=0 if判断的时候会把他当作bool值中0
假:0,False,None,[],(),{},a=''
注意:循环控制当中同等级别的代码必须需要有相同缩进
1 是真
数字都是真
但是0 是假
空是假
练习1:逐一显示列表中的元素
while和for都尝试以下
for循环遍历>>> array = [1,2,3,4,5,6]>>> for i in array :... print i... ... 123456
while循环遍历>>> array = [1,2,3,4,5,6]>>> i = 0>>> while i < num :... print array[i]... i +=1... ... 123456
总结:while和for循环都是很有用的循环遍历方式,一般在对一个步长是1的对象进行遍历使用for循环非常简单,如果步长不是1使用while循环可以自定义控制循环的步长。
练习2:求100以内的所有的偶数和
>>> i = 0>>> num = 0>>> while i < 100 :... num = num +i... i +=2... ... >>> print num2450
练习3:逐一显示指定字典的所有键,并显示总键数
>>> a = {'u1':'u','u2':'uu'}>>> a{'u1': 'u', 'u2': 'uu'}>>> print a.keys()['u1', 'u2']>>> >>> b = a.keys()>>> print len(b)2
练习4:创建一个包含了100以内的所有的奇数
>>> a = [1]>>> i = 1>>> while i <= 100 :... a.append(i)... i +=1... ... >>> print a[1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]>>>
练习5:逆序显示一个列表当中的所有元素
# 下面先做正序显示>>> a = [1,2,3,4,5]>>> print a[0::1] ## 第一个0是从索引为0的开始,第一个和第二个冒泡直接应该写到哪个索引结束,第二个冒泡后面是步长[1, 2, 3, 4, 5]# 下面做反序显示>>> print a[::-1][5, 4, 3, 2, 1]
练习6:l1=[0,1,2,3,4,5,6]
l2=['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
左边的作为一个新字典的key
右边做为左边key的值
>>> l1=[0,1,2,3,4,5,6]>>> l2=['Sun','Mon','Tue','Wed','Thu','Fri','Sat']>>> key.clear()>>> len1 = len(l1)>>> len2 = len(l2)>>> if len1 == len2 :... i = 0... while i < len1 :... key[l1[i]]=l2[i]... i += 1... ... ... >>> key{0: 'Sun', 1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat'}
代码错误提示总结:
IndentationError:缩进错误
IndexError:索引错误
KeyError:字典的key错误
NameError:名字错误,一般都所未定义
SyntaxError:语法错误,关键字或关键符号错误
AttributeError:属性错误,一般都是没有这个属性
KeyboardInterrupt:程序中断
OSError:系统错误
输入输出总结:
输入raw_input
a = raw_input('please input')
输入的值就赋值给变量a了
接收到值默认为字符串
输出print
print 'hello' 输出一个字符串
print a 输出变量a的值
格式化输出:
print 'hello %s this is %s' %(a,b)
导入模块:
实质上就是导入的一个py文件
import module_name导入模块
import module_name as other_name 导入模块并给模块重命名
from module_name import module_function 导入模块下的一个方法(函数)
import os
os.getcwd():返回当前路径
os.listdir('/opt/') 显示指定路径下的文件或目录名
os.remove('/tmp/1.txt')删除制定普通文件,不能删除目录
os.removedirs('/tmp/1/')
os.rmdir('/tmp/1/')
以上两个指令都是删除目录的
os.path.isfile('/tmp/1')
False
os.path.isfile('/tmp/2.txt')
True
判断给出的路径是否是一个文件
os.path.isdir('/tmp/1')
True
判断给出的路径是否是一个目录
os.path.exists('/tmp/2.txt')
判断给出的路径是否真实存在
os.path.isabs('/opt/123')
判断给出的路径是否是绝对路径
os.path.split('/data/program/python27/bin')
解析路径的dirname和basename
os.name()
platform.uname()
打印操作系统平台信息
os.chmod('/tmp/2.txt',0777)
修改文件或目录的权限,记住要带第一位的权限位
os.rename('/tmp/2.txt','/tmp/3.txt')
重命名文件或目录
os.makedirs('/tmp/4/3/2/1')
创建多级目录
os.mkdir('/tmp/4')
创建单级目录
os.stat('/tmp/3.txt')
返回文件或目录的属性
文件的操作:
open:
打开一个文件
打开文件的权限
w:以写的方式打开,如果文件不存在就创建
a:以追加,不会把原文件内容清空
r:以只读
r+:以读写
w+:以读写
w和w+的方式都会把原文件内容清空类似与覆盖追加
rb:
wb:
rb+:
wb+:
打印输出:
read():读取open打开的文件内容,默认全部
readline():读取每一行返回的字符串
readlines():读取多行返回的列表
open(path,mode)
fp = open('/tmp/3.txt',r)
fp.read()
fp.readline()
fp.readlines()
以上只能读取文件内容不能修改
fp.close()
关闭文件对象
fp = open('/tmp/3.txt',w),open('/tmp/3.txt',w+)
fp.write()
fp.writelines()
注意:会覆盖掉原文件内容
关闭之后内容才会保存至硬盘上的文件
fp.close()
fp = open('/tmp/3.txt',a)
以追加方式打开文件
原文件内容不会被覆盖
同样也是需要关闭文件对象
fp.close()
with open('3.txt',a) as 变量:
变量.write()
变量.read()
他会自动的执行变量.close()
fp = open('/tmp/3.txt',r)
fp.tell():打印当前光标所在文件的字符位数上
fp.seek(1):把光标移动倒文件当前的位置
fp.seek(2):把光标移动倒文件末尾位置
拷贝文件或目录
import shutil
shutil.copyfile(src,dst) 只能拷贝文件
shutil.copytree(src,dst)拷贝目录为一个新的名称的目录
import sys
sys.argv:打印所有参数
sys.argv[0]:打印文件名
sys.argv[1]:打印第一个参数
sys.argv[2]:打印第二参数
len(sys.argv):打印参数个数
例子,用Python写一个能显示下一天的脚本
1 #!/data/program/python2.7/bin/python2.7 2 #_*_ coding:utf8 _*_ 3 # 4 # 5 # 6 # 2016 7 # aut wangzilong 8 # 9 # 用python 写一个时间处理的方法 10 # 11 12 import os 13 import sys 14 import re 15 import datetime 16 import time 17 18 # 1 定义函数,定义传参数的函数 19 def mydate(in_day,local_time=time.time()): 20 if in_day == '+1 day': 21 # 一天24小时,一小时60分钟,一分钟60秒,所以一天就是24*60*60=86400秒 22 in_day = 86400 23 print datetime.datetime.fromtimestamp(local_time+in_day).strftime("%Y-%m-%d %H:%M:%S") 24 25 # 2 调用,调用的时候判断参数的个数 26 27 if len(sys.argv) >= 2: 28 day = sys.argv[1] 29 mydate(day) 30 else: 31 mydate(in_day=0)
验证结果:
[root@wzlvm tmp]# ./1.py '+1 day'2016-11-01 20:15:44
例子:用Python写一个求阶乘的脚本
1 #!/data/program/python2.7/bin/python2.7 2 #_*_ coding:utf8 _*_ 3 # 4 # 5 # 6 # 2016 7 # aut wangzilong 8 # 9 # 10 # 11 12 import os 13 import sys 14 import re 15 import datetime 16 import time 17 18 # 1 定义函数 19 20 def jc(in_par=1): 21 if in_par >1: 22 # 递归调用 23 return in_par * jc(in_par-1) 24 else: 25 return in_par 26 27 # 2 调用函数 28 nums = len(sys.argv) 29 if nums > 1: 30 last = jc(int(sys.argv[1])) 31 else: 32 last = jc() 33 print last
验证结果:
[root@wzlvm tmp]# ./jiecheng.py 103628800[root@wzlvm tmp]# ./jiecheng.py 424
例子:输出/etc/passwd文件中打开目录是/bin/bash 的所有用户的用户名
1 #!/data/program/python2.7/bin/python2.7 2 #_*_ coding:utf8 _*_ 3 # 4 # 5 # 6 # 2016 7 # aut wangzilong 8 # 9 # 10 # 11 12 import os 13 import sys 14 import re 15 import datetime 16 import time 17 18 # in_path 输入要匹配的文件路径 19 # in_str 输入要匹配的字符串 20 # in_type 输入文件打开的方式,默认是只读打开 21 22 # 1 定义函数 23 def readpasswd(in_path,in_str,in_type='r'): 24 # 打开文件 25 file = open(in_path,in_type) 26 # 判断是否打开文件 27 if file : 28 # 读取文件 29 file_list = file.readlines() 30 for i in file_list: 31 # 搜索匹配 32 if re.findall(in_str,i): 33 print re.split(":",i)[0] 34 else: 35 print '文件无法打开' 36 file.close() 37 38 # 2 调用函数 39 40 # 获取所有参数 41 argv_list = sys.argv 42 if len(argv_list) >=2: 43 readpasswd(in_path=argv_list[1],in_str=argv_list[2]) 44 else: 45 print '请输入文件路径'
验证结果:
[root@wzlvm tmp]# ./read_file.py '/tmp/passwd.bak' '/bin/bash'rootuser1user3user4t1t2userftp
当然,这个脚本也可以匹配/sbin/nologin的用户,以及匹配其他条件都可以