import 模块html
一、定义:node
模块:用来从逻辑上组织python代码(变量、函数、类、逻辑:实现一个功能),本质就是.py结尾的python文件(文件名test.py 模块名:test)python
2导入方法:git
import test正则表达式
import test,test1算法
from test import t1,t2shell
from test import t1 as long_test编程
三、import 本质(路径搜索,搜索路径)json
导入模块的本质就是把python文件解释一遍windows
import test ----->test.py----->test.py的路径
导入包的本质就是执行该包下的__init__.py文件
__init__.py 引导到当前的模块里 能够写 from . import test1
四、导入优化
from test import t1
五、模块分类
a:标准库或内置模块
b:开源模块或第三方模块
c:自定义模块
--------------------------------------
一:介绍
模块定义:模块就是实现了某个功能的代码集合,一个模块能够定义函数,类和变量。模块还能够包括可运行的代码。
优势:代码重用,可维护性高
语法:
导入单一模块:
1
|
import
module_name
|
导入多个模块
1
|
import
module_name1,module_name2,......
|
调用符号:.
1
2
3
|
import
os
print
(os.sep)
print
(os.getcwd())
|
模块与文件关系:一个.py文件即一个模块,反之亦然。
1
2
3
4
5
|
对于一个模块test有以下定义:
模块的文件名:test.py
模块名:test
模块导入:
import
test
|
二:模块的名称空间(做用域)
定义:名称空间就是一个从名称到对象的关系映射,每一个模块都定义了本身的名称空间,即每一个模块有本身独立的做用域。
分类:python程序在运行时具备三个名称空间,内建(__builtin__模块),全局,局部,python解释器先加载内建名称空间,后加载全局名称空间,最后加载局部名称空间。
名称空间与做用域关系:从内往外找,以较内层做用域为准
示例一:
module_a.py
1
2
3
4
5
6
|
x
=
1
def
test():
print
(
'from the module module_a'
)
module_b.py内容以下
|
module_b.py
1
2
3
4
|
x
=
2
def
test():
print
(
'from the module module_b'
)
|
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import
module_a
import
module_b
print
(module_a.x)
print
(module_b.x)
print
(module_a.x
+
module_b.x)
module_a.test()
module_b.test()
运行结果:
1
2
3
from
the module module_a
from
the module module_b
|
示例二:
module_a.py
1
2
3
4
|
x
=
1
def
test():
print
(
'from the module module_a'
,x)
|
test.py
1
2
3
4
5
|
import
module_a
x
=
2
print
(child_module.x)
child_module.x
=
10
print
(child_module.x)
|
三:模块的搜索路径和路径搜索
模块导入须要经历路径搜索的过程,路径搜索就是在你预约义的搜素路径里查找你想要导入的模块
若是在预约义路径为找到,抛出异常(pycharm的特殊功能除外)
自定义模块b在父级目录里(若有特殊须要可使用sys.path.insert()方法)
解决:
1
2
3
4
5
6
|
import
sys,os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import
b
b.test()
|
四:from-import语句和as
五:包
定义:包就是一组模块的集合
包与目录的区别:包必须包含一个空文件(也能够有内容)__init__
六:阻止属性导入
若是你不想让某个模块属性被 "from module import *" 导入 , 那么你能够给你不想导入的属性名称加上一个下划线( _ )。 不过若是你导入了整个模块或是你显式地导入某个属性这个隐藏数据的方法就不起做用了。
示例一:
module_test.py
1
2
3
4
5
|
def
foo():
print
(
'from the func foo'
)
def
_bar():
print
(
'from the func bar'
)
|
test.py
1
2
3
4
5
6
7
|
from
child_module
import
*
foo()
bar()
抛出异常:
NameError: name
'bar'
is
not
defined
|
示例二:
module_test.py
1
2
3
4
5
|
def
foo():
print
(
'from the func foo'
)
def
_bar():
print
(
'from the func bar'
)
|
test.py
1
2
3
4
|
from
child_module
import
_bar
_bar()
正常运行
|
七:导入循环(交叉引用)与import原理
导入循环:两个模块互相导入
import原理:将导入的模块执行一遍
在python开发过程当中,应尽可能避免导入循环(交叉引用),可是,若是你开发了大型的 Python 工程, 那么你极可能会陷入这样的境地。
解决方法:
将 import 语句移到函数的内部,只有在执行到这个模块时,才会导入相关模块。
错误示范:
b.py
1
2
3
4
5
6
7
8
|
import
os
import
a
def
get_size(file_path):
if
a.file_exists(file_path):
file_size
=
os.path.getsize(file_path)
print
(
'the file %s size is[%s]'
%
(file_path,file_size))
|
a.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import
os
import
b
def
file_exists(file_path):
return
os.path.isfile(file_path)
def
download(file_path):
b.get_size(file_path)
print
(
'download file %s'
%
file_path)
def
upload(file_path):
print
(
'upload file %s'
%
file_path)
download(
'a.txt'
)
|
解决方法:修改b.py
1
2
3
4
5
6
7
|
import
os
def
get_size(file_path):
import
a
if
a.file_exists(file_path):
file_size
=
os.path.getsize(file_path)
print
(
'the file %s size is[%s]'
%
(file_path,file_size))
|
a.py不变
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import
os
import
b
def
file_exists(file_path):
return
os.path.isfile(file_path)
def
download(file_path):
b.get_size(file_path)
print
(
'download file %s'
%
file_path)
def
upload(file_path):
print
(
'upload file %s'
%
file_path)
download(
'a.txt'
)
|
模块分为三种:
内置模块
开源模块
自定义模块
一:自定义模块
1.定义模块:即编写具备某一功能的python文件ftp.py,ftp既模块名
ftp.py
1
2
3
4
5
|
def
get(file_path):
print
(
'download file %s'
%
file_path)
def
put(file_path):
print
(
'download file %s'
%
file_path)
|
2.模块导入方式
import ftp
from ftp import get
from ftp import put as upload
from ftp import *
3.名称空间
4.import的本质
导入一个模块本质就是解释执行一个python文件
导入一个包本质就是解释该包下的__init__.py文件
5.搜索路径与sys.path操做
二:开源模块
1.定义模块:下载安装
方式一:
yum pip apt-get ...
方式二:
下载源码 解压源码 进入目录 编译源码 python setup.py build 安装源码 python setup.py install
注:在使用源码安装时,须要使用到gcc编译和python开发环境,因此,须要先执行:
1
2
3
4
|
yum install gcc
yum install python
-
devel
或
apt
-
get python
-
dev
|
安装成功后,模块会自动安装到 sys.path 中的某个目录中,如:
1
|
/
usr
/
lib
/
python2.
7
/
site
-
packages
/
|
2.导入模块(同自定义模块方式)
3:paramiko
i:下载安装
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# pycrypto,因为 paramiko 模块内部依赖pycrypto,因此先下载安装pycrypto
# 下载安装 pycrypto
wget http:
/
/
files.cnblogs.com
/
files
/
wupeiqi
/
pycrypto
-
2.6
.
1.tar
.gz
tar
-
xvf pycrypto
-
2.6
.
1.tar
.gz
cd pycrypto
-
2.6
.
1
python setup.py build
python setup.py install
# 进入python环境,导入Crypto检查是否安装成功
# 下载安装 paramiko
wget http:
/
/
files.cnblogs.com
/
files
/
wupeiqi
/
paramiko
-
1.10
.
1.tar
.gz
tar
-
xvf paramiko
-
1.10
.
1.tar
.gz
cd paramiko
-
1.10
.
1
python setup.py build
python setup.py install
# 进入python环境,导入paramiko检查是否安装成功
|
ii.使用模块
1. 基于用户名和密码的 sshclient 方式登陆
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import
paramiko
# 创建一个sshclient对象
ssh
=
paramiko.SSHClient()
# 容许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 调用connect方法链接服务器
ssh.connect(hostname
=
'172.16.209.19'
,port
=
22
,username
=
'root'
,password
=
'123'
)
# 执行命令
stdin, stdout, stderr
=
ssh.exec_command(
'df -hl'
)
# 结果放到stdout中,若是有错误将放到stderr中
print
(stdout.read().decode())
# 关闭链接
ssh.close()
|
注意:以sshclient方式运行交互式命令须要增长两行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import
paramiko
# 创建一个sshclient对象
ssh
=
paramiko.SSHClient()
# 容许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 调用connect方法链接服务器
ssh.connect(hostname
=
'172.16.209.119'
,port
=
22
,username
=
'root'
,password
=
'123'
)
# 执行命令
stdin, stdout, stderr
=
ssh.exec_command(
"passwd lhf"
)
# 结果放到stdout中,若是有错误将放到stderr中
stdin.write(
'123\n'
)
stdin.flush()
stdin.write(
'123\n'
)
stdin.flush()
print
(stderr.read())
# 关闭链接
ssh.close()
|
2 基于用户名和密码的 transport 方式登陆
其实paramiko.SSHClient().connect()这个方法的内部实现调用的就是Transport().connect()这个方法。因此能够认为Transport()是paramiko里面建立链接的通用方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#!/usr/bin/python
import
paramiko
# 实例化一个transport对象
trans
=
paramiko.Transport((
'172.16.209.119'
,
22
))
# 创建链接
trans.connect(username
=
'root'
, password
=
'123'
)
# 将sshclient的对象的transport指定为以上的trans
ssh
=
paramiko.SSHClient()
ssh._transport
=
trans
# 执行命令,和传统方法同样
stdin, stdout, stderr
=
ssh.exec_command(
'df -hl'
)
print
(stdout.read().decode())
# 关闭链接
trans.close()
|
3.基于公钥密钥的 SSHClient 方式登陆
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#!/usr/bin/python
import
paramiko
# 指定本地的RSA私钥文件,若是创建密钥对时设置的有密码,password为设定的密码,如无不用指定password参数
pkey
=
paramiko.RSAKey.from_private_key_file(
'D:\id_rsa'
,password
=
'123456'
)
# 创建链接
ssh
=
paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname
=
'172.16.209.119'
,
port
=
22
,
username
=
'root'
,
pkey
=
pkey)
# 执行命令
stdin, stdout, stderr
=
ssh.exec_command(
'df -hl'
)
# 结果放到stdout中,若是有错误将放到stderr中
print
(stdout.read().decode())
# 关闭链接
ssh.close()
|
4 .基于密钥的 Transport 方式登陆
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#!/usr/bin/python
import
paramiko
# 指定本地的RSA私钥文件,若是创建密钥对时设置的有密码,password为设定的密码,如无不用指定password参数
pkey
=
paramiko.RSAKey.from_private_key_file(
'D:\id_rsa'
, password
=
'123456'
)
# 创建链接
trans
=
paramiko.Transport((
'172.16.209.119'
,
22
))
trans.connect(username
=
'root'
, pkey
=
pkey)
# 将sshclient的对象的transport指定为以上的trans
ssh
=
paramiko.SSHClient()
ssh._transport
=
trans
# 执行命令,和传统方法同样
stdin, stdout, stderr
=
ssh.exec_command(
'df -hl'
)
print
(stdout.read().decode())
# 关闭链接
trans.close()
|
传文件 SFTP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#!/usr/bin/python
import
paramiko
# 实例化一个trans对象# 实例化一个transport对象
trans
=
paramiko.Transport((
'172.16.209.119'
,
22
))
# 创建链接
trans.connect(username
=
'root'
, password
=
'123'
)
# 实例化一个 sftp对象,指定链接的通道
sftp
=
paramiko.SFTPClient.from_transport(trans)
# 发送文件
sftp.put(localpath
=
'D:\id_rsa'
, remotepath
=
'/tmp/id_rsa'
)
# 下载文件
# sftp.get(remotepath, localpath)
trans.close()
|
三:内置模块
os模块
用于提供系统级别的操做
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
|
os.getcwd() 获取当前工做目录,即当前python脚本工做的目录路径
os.chdir(
"dirname"
) 改变当前脚本工做目录;至关于shell下cd
os.curdir 返回当前目录: (
'.'
)
os.pardir 获取当前目录的父目录字符串名:(
'..'
)
os.makedirs(
'dirname1/dirname2'
) 可生成多层递归目录
os.removedirs(
'dirname1'
) 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir(
'dirname'
) 生成单级目录;至关于shell中mkdir dirname
os.rmdir(
'dirname'
) 删除单级空目录,若目录不为空则没法删除,报错;至关于shell中rmdir dirname
os.listdir(
'dirname'
) 列出指定目录下的全部文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() 删除一个文件
os.rename(
"oldname"
,
"newname"
) 重命名文件
/
目录
os.stat(
'path/filename'
) 获取文件
/
目录信息
os.sep 输出操做系统特定的路径分隔符,win下为
"\\",Linux下为"
/
"os.linesep 输出当前平台使用的行终止符,win下为"
\t\n
",Linux下为"
\n"os.pathsep 输出用于分割文件路径的字符串
os.name 输出字符串指示当前使用平台。win
-
>
'nt'
; Linux
-
>
'posix'
os.system(
"bash command"
) 运行shell命令,直接显示
os.environ 获取系统环境变量
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回,它仅仅是以
"PATH"
中最后一个
'/'
做为分隔符,分隔后,将索引为
0
的视为目录(路径),将索引为
1
的视为文件名
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 若是path存在,返回
True
;若是path不存在,返回
False
os.path.isabs(path) 若是path是绝对路径,返回
True
os.path.isfile(path) 若是path是一个存在的文件,返回
True
。不然返回
False
os.path.isdir(path) 若是path是一个存在的目录,则返回
True
。不然返回
False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径以前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
|
os.path.join示范
1
2
3
4
5
6
|
>>> os.path.join(
'c:\\', '
csv
', '
test.csv')
'c:\\csv\\test.csv'
>>> os.path.join(
'windows\temp'
,
'c:\\', '
csv
', '
test.csv')
'c:\\csv\\test.csv'
>>> os.path.join(
'/home/aa'
,
'/home/aa/bb'
,
'/home/aa/bb/c'
)
'/home/aa/bb/c'
|
time和datetime(http://www.jb51.net/article/49326.htm)
在Python中,一般有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串 3)元组(struct_time)共九个元素。因为Python的time模块实现主要调用C库,因此各个平台可能有所不一样。
UTC(Coordinated Universal Time,世界协调时)亦即格林威治天文时间,世界标准时间。在中国为UTC+8。DST(Daylight Saving Time)即夏令时。
时间戳(timestamp)的方式:一般来讲,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。咱们运行“type(time.time())”,返回的是float类型。返回时间戳方式的函数主要有time(),clock()等。
元组(struct_time)方式:struct_time元组共有9个元素,返回struct_time的函数主要有gmtime(),localtime(),strptime()。下面列出这种方式元组中的几个元素:
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
|
#_*_coding:utf-8_*_
import
time
# print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改为了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
# print(time.altzone) #返回与utc时间的时间差,以秒计算\
# print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
# print(time.localtime()) #返回本地时间 的struct time对象格式
# print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式
# print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",
#print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上
# 日期字符串 转成 时间戳
# string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
# print(string_2_struct)
# #
# struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
# print(struct_2_stamp)
#将时间戳转为字符串格式
# print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
# print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式
#时间加减
import
datetime
# print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
#print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2016-08-19
# print(datetime.datetime.now() )
# print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
# print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
# print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
# print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
#
# c_time = datetime.datetime.now()
# print(c_time.replace(minute=3,hour=2)) #时间替换
|
格式参照
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
%
a 本地(locale)简化星期名称
%
A 本地完整星期名称
%
b 本地简化月份名称
%
B 本地完整月份名称
%
c 本地相应的日期和时间表示
%
d 一个月中的第几天(
01
-
31
)
%
H 一天中的第几个小时(
24
小时制,
00
-
23
)
%
I 第几个小时(
12
小时制,
01
-
12
)
%
j 一年中的第几天(
001
-
366
)
%
m 月份(
01
-
12
)
%
M 分钟数(
00
-
59
)
%
p 本地am或者pm的相应符 一
%
S 秒(
01
-
61
) 二
%
U 一年中的星期数。(
00
-
53
星期天是一个星期的开始。)第一个星期天以前的全部天数都放在第
0
周。 三
%
w 一个星期中的第几天(
0
-
6
,
0
是星期天) 三
%
W 和
%
U基本相同,不一样的是
%
W以星期一为一个星期的开始。
%
x 本地相应日期
%
X 本地相应时间
%
y 去掉世纪的年份(
00
-
99
)
%
Y 完整的年份
%
Z 时区的名字(若是不存在为空字符)
%
%
‘
%
’字符
|
时间关系转换
更多点击这里
2.random模块
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#!/usr/bin/env python
#_*_encoding: utf-8_*_
import
random
print
(random.random())
#0.6445010863311293
#random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0
print
(random.randint(
1
,
7
))
#4
#random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。
# 其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
print
(random.randrange(
1
,
10
))
#5
#random.randrange的函数原型为:random.randrange([start], stop[, step]),
# 从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),
# 结果至关于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。
# random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。
print
(random.choice(
'liukuni'
))
#i
#random.choice从序列中获取一个随机元素。
# 其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。
# 这里要说明一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。
# list, tuple, 字符串都属于sequence。有关sequence能够查看python手册数据模型这一章。
# 下面是使用choice的一些例子:
print
(random.choice(
"学习Python"
))
#学
print
(random.choice([
"JGood"
,
"is"
,
"a"
,
"handsome"
,
"boy"
]))
#List
print
(random.choice((
"Tuple"
,
"List"
,
"Dict"
)))
#List
print
(random.sample([
1
,
2
,
3
,
4
,
5
],
3
))
#[1, 2, 5]
#random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片段。sample函数不会修改原有序列。
|
实际应用:
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
|
#!/usr/bin/env python
# encoding: utf-8
import
random
import
string
#随机整数:
print
( random.randint(
0
,
99
))
#70
#随机选取0到100间的偶数:
print
(random.randrange(
0
,
101
,
2
))
#4
#随机浮点数:
print
( random.random())
#0.2746445568079129
print
(random.uniform(
1
,
10
))
#9.887001463194844
#随机字符:
print
(random.choice(
'abcdefg&#%^*f'
)) #f
#多个字符中选取特定数量的字符:
print
(random.sample(
'abcdefghij'
,
3
))
#['f', 'h', 'd']
#随机选取字符串:
print
( random.choice ( [
'apple'
,
'pear'
,
'peach'
,
'orange'
,
'lemon'
] ))
#apple
#洗牌#
items
=
[
1
,
2
,
3
,
4
,
5
,
6
,
7
]
print
(items)
#[1, 2, 3, 4, 5, 6, 7]
random.shuffle(items)
print
(items)
#[1, 4, 7, 2, 5, 3, 6]
|
生成随机验证码:
1
2
3
4
5
6
7
8
9
10
|
import
random
checkcode
=
''
for
i
in
range
(
4
):
current
=
random.randrange(
0
,
4
)
if
current !
=
i:
temp
=
chr
(random.randint(
65
,
90
))
else
:
temp
=
random.randint(
0
,
9
)
checkcode
+
=
str
(temp)
print
(checkcode)
|
3.os模块
提供对操做系统进行调用的接口
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
|
os.getcwd() 获取当前工做目录,即当前python脚本工做的目录路径
os.chdir(
"dirname"
) 改变当前脚本工做目录;至关于shell下cd
os.curdir 返回当前目录: (
'.'
)
os.pardir 获取当前目录的父目录字符串名:(
'..'
)
os.makedirs(
'dirname1/dirname2'
) 可生成多层递归目录
os.removedirs(
'dirname1'
) 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir(
'dirname'
) 生成单级目录;至关于shell中mkdir dirname
os.rmdir(
'dirname'
) 删除单级空目录,若目录不为空则没法删除,报错;至关于shell中rmdir dirname
os.listdir(
'dirname'
) 列出指定目录下的全部文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() 删除一个文件
os.rename(
"oldname"
,
"newname"
) 重命名文件
/
目录
os.stat(
'path/filename'
) 获取文件
/
目录信息
os.sep 输出操做系统特定的路径分隔符,win下为
"\\",Linux下为"
/
"
os.linesep 输出当前平台使用的行终止符,win下为
"\t\n"
,Linux下为
"\n"
os.pathsep 输出用于分割文件路径的字符串
os.name 输出字符串指示当前使用平台。win
-
>
'nt'
; Linux
-
>
'posix'
os.system(
"bash command"
) 运行shell命令,直接显示
os.environ 获取系统环境变量
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 若是path存在,返回
True
;若是path不存在,返回
False
os.path.isabs(path) 若是path是绝对路径,返回
True
os.path.isfile(path) 若是path是一个存在的文件,返回
True
。不然返回
False
os.path.isdir(path) 若是path是一个存在的目录,则返回
True
。不然返回
False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径以前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
|
更多点击这里
print os.path.getatime("d:\\new") #最后访问时间
print os.path.getmtime("d:\\new") #最后修改路径时间
print os.path.getctime("d:\\new") #建立时间
4.sys模块
1
2
3
4
5
6
7
8
|
sys.argv 命令行参数
List
,第一个元素是程序自己路径
sys.exit(n) 退出程序,正常退出时exit(
0
)
sys.version 获取Python解释程序的版本信息
sys.maxint 最大的
Int
值
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform 返回操做系统平台名称
sys.stdout.write(
'please:'
)
val
=
sys.stdin.readline()[:
-
1
]
|
5.shutil模块
参考http://www.cnblogs.com/wupeiqi/articles/4963027.html
6.json和pickle模块
用于序列化的两个模块
json,用于字符串 和 python数据类型间进行转换
pickle,用于python特有的类型 和 python的数据类型间进行转换
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
7. shelve模块
shelve模块是一个简单的k,v将内存数据经过文件持久化的模块,能够持久化任何pickle可支持的python数据格式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import
shelve
d
=
shelve.
open
(
'shelve_test'
)
#打开一个文件
class
Test(
object
):
def
__init__(
self
,n):
self
.n
=
n
t
=
Test(
123
)
t2
=
Test(
123334
)
name
=
[
"alex"
,
"rain"
,
"test"
]
d[
"test"
]
=
name
#持久化列表
d[
"t1"
]
=
t
#持久化类
d[
"t2"
]
=
t2
d.close()
|
本节大纲:
模块,用一砣代码实现了某个功能的代码集合。
相似于函数式编程和面向过程编程,函数式编程则完成一个功能,其余代码用来调用便可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能须要多个函数才能完成(函数又能够在不一样的.py文件中),n个 .py 文件组成的代码集合就称为模块。
如:os 是系统相关的模块;file是文件操做相关的模块
模块分为三种:
自定义模块 和开源模块的使用参考 http://www.cnblogs.com/wupeiqi/articles/4963027.html
1 1 #_*_coding:utf-8_*_ 2 2 __author__ = 'Alex Li' 3 3 4 4 import time 5 5 6 6 7 7 # print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改为了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来 8 8 # print(time.altzone) #返回与utc时间的时间差,以秒计算\ 9 9 # print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016", 10 10 # print(time.localtime()) #返回本地时间 的struct time对象格式 11 11 # print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式 12 12 13 13 # print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016", 14 14 #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上 15 15 16 16 17 17 18 18 # 日期字符串 转成 时间戳 19 19 # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式 20 20 # print(string_2_struct) 21 21 # # 22 22 # struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳 23 23 # print(struct_2_stamp) 24 24 25 25 26 26 27 27 #将时间戳转为字符串格式 28 28 # print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式 29 29 # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式 30 30 31 31 32 32 33 33 34 34 35 35 #时间加减 36 36 import datetime 37 37 38 38 # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925 39 39 #print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2016-08-19 40 40 # print(datetime.datetime.now() ) 41 41 # print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天 42 42 # print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天 43 43 # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时 44 44 # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分 45 45 46 46 47 47 # 48 48 # c_time = datetime.datetime.now() 49 49 # print(c_time.replace(minute=3,hour=2)) #时间替换
Directive | Meaning | Notes |
---|---|---|
%a |
Locale’s abbreviated weekday name. | |
%A |
Locale’s full weekday name. | |
%b |
Locale’s abbreviated month name. | |
%B |
Locale’s full month name. | |
%c |
Locale’s appropriate date and time representation. | |
%d |
Day of the month as a decimal number [01,31]. | |
%H |
Hour (24-hour clock) as a decimal number [00,23]. | |
%I |
Hour (12-hour clock) as a decimal number [01,12]. | |
%j |
Day of the year as a decimal number [001,366]. | |
%m |
Month as a decimal number [01,12]. | |
%M |
Minute as a decimal number [00,59]. | |
%p |
Locale’s equivalent of either AM or PM. | (1) |
%S |
Second as a decimal number [00,61]. | (2) |
%U |
Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. | (3) |
%w |
Weekday as a decimal number [0(Sunday),6]. | |
%W |
Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. | (3) |
%x |
Locale’s appropriate date representation. | |
%X |
Locale’s appropriate time representation. | |
%y |
Year without century as a decimal number [00,99]. | |
%Y |
Year with century as a decimal number. | |
%z |
Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59]. | |
%Z |
Time zone name (no characters if no time zone exists). | |
%% |
A literal '%' character. |
随机数
1
2
3
4
|
mport random
print
random.random()
print
random.randint(
1
,
2
)
print
random.randrange(
1
,
10
)
|
生成随机验证码
1
2
3
4
5
6
7
8
9
10
|
import
random
checkcode
=
''
for
i
in
range
(
4
):
current
=
random.randrange(
0
,
4
)
if
current !
=
i:
temp
=
chr
(random.randint(
65
,
90
))
else
:
temp
=
random.randint(
0
,
9
)
checkcode
+
=
str
(temp)
print
checkcode
|
提供对操做系统进行调用的接口
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
|
os.getcwd() 获取当前工做目录,即当前python脚本工做的目录路径
os.chdir(
"dirname"
) 改变当前脚本工做目录;至关于shell下cd
os.curdir 返回当前目录: (
'.'
)
os.pardir 获取当前目录的父目录字符串名:(
'..'
)
os.makedirs(
'dirname1/dirname2'
) 可生成多层递归目录
os.removedirs(
'dirname1'
) 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir(
'dirname'
) 生成单级目录;至关于shell中mkdir dirname
os.rmdir(
'dirname'
) 删除单级空目录,若目录不为空则没法删除,报错;至关于shell中rmdir dirname
os.listdir(
'dirname'
) 列出指定目录下的全部文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() 删除一个文件
os.rename(
"oldname"
,
"newname"
) 重命名文件
/
目录
os.stat(
'path/filename'
) 获取文件
/
目录信息
os.sep 输出操做系统特定的路径分隔符,win下为
"\\",Linux下为"
/
"
os.linesep 输出当前平台使用的行终止符,win下为
"\t\n"
,Linux下为
"\n"
os.pathsep 输出用于分割文件路径的字符串
os.name 输出字符串指示当前使用平台。win
-
>
'nt'
; Linux
-
>
'posix'
os.system(
"bash command"
) 运行shell命令,直接显示
os.environ 获取系统环境变量
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 若是path存在,返回
True
;若是path不存在,返回
False
os.path.isabs(path) 若是path是绝对路径,返回
True
os.path.isfile(path) 若是path是一个存在的文件,返回
True
。不然返回
False
os.path.isdir(path) 若是path是一个存在的目录,则返回
True
。不然返回
False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径以前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
|
更多猛击这里
1
2
3
4
5
6
7
8
|
sys.argv 命令行参数
List
,第一个元素是程序自己路径
sys.exit(n) 退出程序,正常退出时exit(
0
)
sys.version 获取Python解释程序的版本信息
sys.maxint 最大的
Int
值
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform 返回操做系统平台名称
sys.stdout.write(
'please:'
)
val
=
sys.stdin.readline()[:
-
1
]
|
直接参考 http://www.cnblogs.com/wupeiqi/articles/4963027.html
高级的 文件、文件夹、压缩包 处理模块
shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另外一个文件中,能够部份内容
shutil.copyfile(src, dst)
拷贝文件
shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变
shutil.copystat(src, dst)
拷贝状态的信息,包括:mode bits, atime, mtime, flags
shutil.copy(src, dst)
拷贝文件和权限
shutil.copy2(src, dst)
拷贝文件和状态信息
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件
shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件
shutil.move(src, dst)
递归的去移动文件
shutil.make_archive(base_name, format,...)
建立压缩包并返回文件路径,例如:zip、tar
1
2
3
4
5
6
7
8
9
|
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
import
shutil
ret
=
shutil.make_archive(
"wwwwwwwwww"
,
'gztar'
, root_dir
=
'/Users/wupeiqi/Downloads/test'
)
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
import
shutil
ret
=
shutil.make_archive(
"/Users/wupeiqi/wwwwwwwwww"
,
'gztar'
, root_dir
=
'/Users/wupeiqi/Downloads/test'
)
|
1 import zipfile 2 3 # 压缩 4 z = zipfile.ZipFile('laxi.zip', 'w') 5 z.write('a.log') 6 z.write('data.data') 7 z.close() 8 9 # 解压 10 z = zipfile.ZipFile('laxi.zip', 'r') 11 z.extractall() 12 z.close() 13 复制代码
1 import tarfile 2 3 # 压缩 4 tar = tarfile.open('your.tar','w') 5 tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip') 6 tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip') 7 tar.close() 8 9 # 解压 10 tar = tarfile.open('your.tar','r') 11 tar.extractall() # 可设置解压地址 12 tar.close()
用于序列化的两个模块
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
shelve模块是一个简单的k,v将内存数据经过文件持久化的模块,能够持久化任何pickle可支持的python数据格式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import
shelve
d
=
shelve.
open
(
'shelve_test'
)
#打开一个文件
class
Test(
object
):
def
__init__(
self
,n):
self
.n
=
n
t
=
Test(
123
)
t2
=
Test(
123334
)
name
=
[
"alex"
,
"rain"
,
"test"
]
d[
"test"
]
=
name
#持久化列表
d[
"t1"
]
=
t
#持久化类
d[
"t2"
]
=
t2
d.close()
|
xml是实现不一样语言或程序之间进行数据交换的协议,跟json差很少,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,你们只能选择用xml呀,至今不少传统公司如金融行业的不少系统的接口还主要是xml。
xml的格式以下,就是经过<>节点来区别数据结构的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<?
xml
version="1.0"?>
<
data
>
<
country
name="Liechtenstein">
<
rank
updated="yes">2</
rank
>
<
year
>2008</
year
>
<
gdppc
>141100</
gdppc
>
<
neighbor
name="Austria" direction="E"/>
<
neighbor
name="Switzerland" direction="W"/>
</
country
>
<
country
name="Singapore">
<
rank
updated="yes">5</
rank
>
<
year
>2011</
year
>
<
gdppc
>59900</
gdppc
>
<
neighbor
name="Malaysia" direction="N"/>
</
country
>
<
country
name="Panama">
<
rank
updated="yes">69</
rank
>
<
year
>2011</
year
>
<
gdppc
>13600</
gdppc
>
<
neighbor
name="Costa Rica" direction="W"/>
<
neighbor
name="Colombia" direction="E"/>
</
country
>
</
data
>
|
xml协议在各个语言里的都 是支持的,在python中能够用如下模块操做xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import
xml.etree.ElementTree as ET
tree
=
ET.parse(
"xmltest.xml"
)
root
=
tree.getroot()
print
(root.tag)
#遍历xml文档
for
child
in
root:
print
(child.tag, child.attrib)
for
i
in
child:
print
(i.tag,i.text)
#只遍历year 节点
for
node
in
root.
iter
(
'year'
):
print
(node.tag,node.text)
|
修改和删除xml文档内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import
xml.etree.ElementTree as ET
tree
=
ET.parse(
"xmltest.xml"
)
root
=
tree.getroot()
#修改
for
node
in
root.
iter
(
'year'
):
new_year
=
int
(node.text)
+
1
node.text
=
str
(new_year)
node.
set
(
"updated"
,
"yes"
)
tree.write(
"xmltest.xml"
)
#删除node
for
country
in
root.findall(
'country'
):
rank
=
int
(country.find(
'rank'
).text)
if
rank >
50
:
root.remove(country)
tree.write(
'output.xml'
)
|
本身建立xml文档
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import
xml.etree.ElementTree as ET
new_xml
=
ET.Element(
"namelist"
)
name
=
ET.SubElement(new_xml,
"name"
,attrib
=
{
"enrolled"
:
"yes"
})
age
=
ET.SubElement(name,
"age"
,attrib
=
{
"checked"
:
"no"
})
sex
=
ET.SubElement(name,
"sex"
)
sex.text
=
'33'
name2
=
ET.SubElement(new_xml,
"name"
,attrib
=
{
"enrolled"
:
"no"
})
age
=
ET.SubElement(name2,
"age"
)
age.text
=
'19'
et
=
ET.ElementTree(new_xml)
#生成文档对象
et.write(
"test.xml"
, encoding
=
"utf-8"
,xml_declaration
=
True
)
ET.dump(new_xml)
#打印生成的格式
|
Python也能够很容易的处理ymal文档格式,只不过须要安装一个模块,参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation
用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变动为 configparser。
来看一个好多软件的常见文档格式以下
1
2
3
4
5
6
7
8
9
10
11
12
|
[DEFAULT]
ServerAliveInterval
=
45
Compression
=
yes
CompressionLevel
=
9
ForwardX11
=
yes
[bitbucket.org]
User
=
hg
[topsecret.server.com]
Port
=
50022
ForwardX11
=
no
|
若是想用python生成一个这样的文档怎么作呢?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import
configparser
config
=
configparser.ConfigParser()
config[
"DEFAULT"
]
=
{
'ServerAliveInterval'
:
'45'
,
'Compression'
:
'yes'
,
'CompressionLevel'
:
'9'
}
config[
'bitbucket.org'
]
=
{}
config[
'bitbucket.org'
][
'User'
]
=
'hg'
config[
'topsecret.server.com'
]
=
{}
topsecret
=
config[
'topsecret.server.com'
]
topsecret[
'Host Port'
]
=
'50022'
# mutates the parser
topsecret[
'ForwardX11'
]
=
'no'
# same here
config[
'DEFAULT'
][
'ForwardX11'
]
=
'yes'
with
open
(
'example.ini'
,
'w'
) as configfile:
config.write(configfile)
|
写完了还能够再读出来哈。
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
|
>>>
import
configparser
>>> config
=
configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read(
'example.ini'
)
[
'example.ini'
]
>>> config.sections()
[
'bitbucket.org'
,
'topsecret.server.com'
]
>>>
'bitbucket.org'
in
config
True
>>>
'bytebong.com'
in
config
False
>>> config[
'bitbucket.org'
][
'User'
]
'hg'
>>> config[
'DEFAULT'
][
'Compression'
]
'yes'
>>> topsecret
=
config[
'topsecret.server.com'
]
>>> topsecret[
'ForwardX11'
]
'no'
>>> topsecret[
'Port'
]
'50022'
>>>
for
key
in
config[
'bitbucket.org'
]:
print
(key)
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config[
'bitbucket.org'
][
'ForwardX11'
]
'yes'
|
configparser增删改查语法
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
|
[section1]
k1
=
v1
k2:v2
[section2]
k1
=
v1
import
ConfigParser
config
=
ConfigParser.ConfigParser()
config.read(
'i.cfg'
)
# ########## 读 ##########
#secs = config.sections()
#print secs
#options = config.options('group2')
#print options
#item_list = config.items('group2')
#print item_list
#val = config.get('group1','key')
#val = config.getint('group1','key')
# ########## 改写 ##########
#sec = config.remove_section('group1')
#config.write(open('i.cfg', "w"))
#sec = config.has_section('wupeiqi')
#sec = config.add_section('wupeiqi')
#config.write(open('i.cfg', "w"))
#config.set('group2','k1',11111)
#config.write(open('i.cfg', "w"))
#config.remove_option('group2','age')
#config.write(open('i.cfg', "w"))
|
hashlib模块
用于加密相关的操做,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
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
|
import
hashlib
m
=
hashlib.md5()
m.update(b
"Hello"
)
m.update(b
"It's me"
)
print
(m.digest())
m.update(b
"It's been a long time since last time we ..."
)
print
(m.digest())
#2进制格式hash
print
(
len
(m.hexdigest()))
#16进制格式hash
'''
def digest(self, *args, **kwargs): # real signature unknown
""" Return the digest value as a string of binary data. """
pass
def hexdigest(self, *args, **kwargs): # real signature unknown
""" Return the digest value as a string of hexadecimal digits. """
pass
'''
import
hashlib
# ######## md5 ########
hash
=
hashlib.md5()
hash
.update(
'admin'
)
print
(
hash
.hexdigest())
# ######## sha1 ########
hash
=
hashlib.sha1()
hash
.update(
'admin'
)
print
(
hash
.hexdigest())
# ######## sha256 ########
hash
=
hashlib.sha256()
hash
.update(
'admin'
)
print
(
hash
.hexdigest())
# ######## sha384 ########
hash
=
hashlib.sha384()
hash
.update(
'admin'
)
print
(
hash
.hexdigest())
# ######## sha512 ########
hash
=
hashlib.sha512()
hash
.update(
'admin'
)
print
(
hash
.hexdigest())
|
还不够吊?python 还有一个 hmac 模块,它内部对咱们建立 key 和 内容 再进行处理而后再加密
散列消息鉴别码,简称HMAC,是一种基于消息鉴别码MAC(Message Authentication Code)的鉴别机制。使用HMAC时,消息通信的双方,经过验证消息中加入的鉴别密钥K来鉴别消息的真伪;
通常用于网络通讯中消息加密,前提是双方先要约定好key,就像接头暗号同样,而后消息发送把用key把消息加密,接收方用key + 消息明文再加密,拿加密后的值 跟 发送者的相对比是否相等,这样就能验证消息的真实性,及发送者的合法性了。
1
2
3
|
import
hmac
h
=
hmac.new(b
'天王盖地虎'
, b
'宝塔镇河妖'
)
print
h.hexdigest()
|
更多关于md5,sha1,sha256等介绍的文章看这里https://www.tbs-certificates.co.uk/FAQ/en/sha256.html
The subprocess
module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:
os.system os.spawn*
The recommended approach to invoking subprocesses is to use the run()
function for all use cases it can handle. For more advanced use cases, the underlying Popen
interface can be used directly.
The run()
function was added in Python 3.5; if you need to retain compatibility with older versions, see the Older high-level API section.
(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False)subprocess.run
Run the command described by args. Wait for command to complete, then return a CompletedProcess
instance.
The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the Popen
constructor - apart from timeout, input and check, all the arguments to this function are passed through to that interface.
This does not capture stdout or stderr by default. To do so, pass PIPE
for the stdout and/or stderr arguments.
The timeout argument is passed to Popen.communicate()
. If the timeout expires, the child process will be killed and waited for. The TimeoutExpired
exception will be re-raised after the child process has terminated.
The input argument is passed to Popen.communicate()
and thus to the subprocess’s stdin. If used it must be a byte sequence, or a string if universal_newlines=True
. When used, the internal Popen
object is automatically created withstdin=PIPE
, and the stdin argument may not be used as well.
If check is True, and the process exits with a non-zero exit code, a CalledProcessError
exception will be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.
#执行命令,返回命令执行状态 , 0 or 非0
>>> retcode = subprocess.call(["ls", "-l"])
#执行命令,若是命令结果为0,就正常返回,不然抛异常
>>> subprocess.check_call(["ls", "-l"])
0
#接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果
>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
#接收字符串格式命令,并返回结果
>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'
#执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res
>>> res=subprocess.check_output(['ls','-l'])
>>> res
b'total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n'
#上面那些方法,底层都是封装的subprocess.Popen
poll()
Check if child process has terminated. Returns returncode
wait()
Wait for child process to terminate. Returns returncode attribute.
terminate() 杀掉所启动进程
communicate() 等待任务结束
stdin 标准输入
stdout 标准输出
stderr 标准错误
pid
The process ID of the child process.
#例子
>>> p = subprocess.Popen("df -h|grep disk",stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
>>> p.stdout.read()
b'/dev/disk1 465Gi 64Gi 400Gi 14% 16901472 104938142 14% /\n'
1
2
3
4
5
6
7
8
9
10
11
|
>>> subprocess.run([
"ls"
,
"-l"
])
# doesn't capture output
CompletedProcess(args
=
[
'ls'
,
'-l'
], returncode
=
0
)
>>> subprocess.run(
"exit 1"
, shell
=
True
, check
=
True
)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command
'exit 1'
returned non
-
zero exit status
1
>>> subprocess.run([
"ls"
,
"-l"
,
"/dev/null"
], stdout
=
subprocess.PIPE)
CompletedProcess(args
=
[
'ls'
,
'-l'
,
'/dev/null'
], returncode
=
0
,
stdout
=
b
'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n'
)
|
调用subprocess.run(...)是推荐的经常使用方法,在大多数状况下能知足需求,但若是你可能须要进行一些复杂的与系统的交互的话,你还能够用subprocess.Popen(),语法以下:
1
2
|
p
=
subprocess.Popen(
"find / -size +1000000 -exec ls -shl {} \;"
,shell
=
True
,stdout
=
subprocess.PIPE)
print
(p.stdout.read())
|
可用参数:
终端输入的命令分为两种:
须要交互的命令示例
1
2
3
4
5
6
7
8
9
10
|
import
subprocess
obj
=
subprocess.Popen([
"python"
], stdin
=
subprocess.PIPE, stdout
=
subprocess.PIPE, stderr
=
subprocess.PIPE)
obj.stdin.write(
'print 1 \n '
)
obj.stdin.write(
'print 2 \n '
)
obj.stdin.write(
'print 3 \n '
)
obj.stdin.write(
'print 4 \n '
)
out_error_list
=
obj.communicate(timeout
=
10
)
print
out_error_list
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import
subprocess
def
mypass():
mypass
=
'123'
#or get the password from anywhere
return
mypass
echo
=
subprocess.Popen([
'echo'
,mypass()],
stdout
=
subprocess.PIPE,
)
sudo
=
subprocess.Popen([
'sudo'
,
'-S'
,
'iptables'
,
'-L'
],
stdin
=
echo.stdout,
stdout
=
subprocess.PIPE,
)
end_of_pipe
=
sudo.stdout
print
"Password ok \n Iptables Chains %s"
%
end_of_pipe.read()
|
不少程序都有记录日志的需求,而且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你能够经过它存储各类格式的日志,logging的日志能够分为 debug()
, info()
, warning()
, error()
and critical() 5个级别,
下面咱们看一下怎么用。
最简单用法
1
2
3
4
5
6
7
8
|
import
logging
logging.warning(
"user [alex] attempted wrong password more than 3 times"
)
logging.critical(
"server is down"
)
#输出
WARNING:root:user [alex] attempted wrong password more than
3
times
CRITICAL:root:server
is
down
|
看一下这几个日志级别分别表明什么意思
Level | When it’s used |
---|---|
DEBUG |
Detailed information, typically of interest only when diagnosing problems. |
INFO |
Confirmation that things are working as expected. |
WARNING |
An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. |
ERROR |
Due to a more serious problem, the software has not been able to perform some function. |
CRITICAL |
A serious error, indicating that the program itself may be unable to continue running. |
若是想把日志写到文件里,也很简单
1
2
3
4
5
6
|
import
logging
logging.basicConfig(filename
=
'example.log'
,level
=
logging.INFO)
logging.debug(
'This message should go to the log file'
)
logging.info(
'So should this'
)
logging.warning(
'And this, too'
)
|
其中下面这句中的level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志才会被纪录到文件里,在这个例子, 第一条日志是不会被纪录的,若是但愿纪录debug的日志,那把日志级别改为DEBUG就好了。
1
|
logging.basicConfig(filename
=
'example.log'
,level
=
logging.INFO)
|
感受上面的日志格式忘记加上时间啦,日志不知道时间怎么行呢,下面就来加上!
1
2
3
4
5
6
|
import
logging
logging.basicConfig(
format
=
'%(asctime)s %(message)s'
, datefmt
=
'%m/%d/%Y %I:%M:%S %p'
)
logging.warning(
'is when this event was logged.'
)
#输出
12
/
12
/
2010
11
:
46
:
36
AM
is
when this event was logged.
|
日志格式
%(name)s |
Logger的名字 |
%(levelno)s |
数字形式的日志级别 |
%(levelname)s |
文本形式的日志级别 |
%(pathname)s |
调用日志输出函数的模块的完整路径名,可能没有 |
%(filename)s |
调用日志输出函数的模块的文件名 |
%(module)s |
调用日志输出函数的模块名 |
%(funcName)s |
调用日志输出函数的函数名 |
%(lineno)d |
调用日志输出函数的语句所在的代码行 |
%(created)f |
当前时间,用UNIX标准的表示时间的浮 点数表示 |
%(relativeCreated)d |
输出日志信息时的,自Logger建立以 来的毫秒数 |
%(asctime)s |
字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 |
%(thread)d |
线程ID。可能没有 |
%(threadName)s |
线程名。可能没有 |
%(process)d |
进程ID。可能没有 |
%(message)s |
用户输出的消息 |
若是想同时把log打印在屏幕和文件日志里,就须要了解一点复杂的知识 了
Python 使用logging模块记录日志涉及四个主要类,使用官方文档中的归纳最为合适:
logger提供了应用程序能够直接使用的接口;
handler将(logger建立的)日志记录发送到合适的目的输出;
filter提供了细度设备来决定输出哪条日志记录;
formatter决定日志记录的最终输出格式。
logger
每一个程序在输出信息以前都要得到一个Logger。Logger一般对应了程序的模块名,好比聊天工具的图形界面模块能够这样得到它的Logger:
LOG=logging.getLogger(”chat.gui”)
而核心模块能够这样:
LOG=logging.getLogger(”chat.kernel”)
Logger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高
Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filter
Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增长或删除指定的handler
Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():能够设置的日志级别
handler
handler对象负责发送相关的信息到指定目的地。Python的日志系统有多种Handler可使用。有些Handler能够把信息输出到控制台,有些Logger能够把信息输出到文件,还有些 Handler能够把信息发送到网络上。若是以为不够用,还能够编写本身的Handler。能够经过addHandler()方法添加多个多handler
Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略
Handler.setFormatter():给这个handler选择一个格式
Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象
每一个Logger能够附加多个Handler。接下来咱们就来介绍一些经常使用的Handler:
1) logging.StreamHandler
使用这个Handler能够向相似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息。它的构造函数是:
StreamHandler([strm])
其中strm参数是一个文件对象。默认是sys.stderr
2) logging.FileHandler
和StreamHandler相似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件。它的构造函数是:
FileHandler(filename[,mode])
filename是文件名,必须指定一个文件名。
mode是文件的打开方式。参见Python内置函数open()的用法。默认是’a',即添加到文件末尾。
3) logging.handlers.RotatingFileHandler
这个Handler相似于上面的FileHandler,可是它能够管理文件大小。当文件达到必定大小以后,它会自动将当前日志文件更名,而后建立 一个新的同名日志文件继续输出。好比日志文件是chat.log。当chat.log达到指定的大小以后,RotatingFileHandler自动把 文件更名为chat.log.1。不过,若是chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。。。最后从新建立 chat.log,继续输出日志信息。它的构造函数是:
RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
其中filename和mode两个参数和FileHandler同样。
maxBytes用于指定日志文件的最大文件大小。若是maxBytes为0,意味着日志文件能够无限大,这时上面描述的重命名过程就不会发生。
backupCount用于指定保留的备份文件的个数。好比,若是指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被改名,而是被删除。
4) logging.handlers.TimedRotatingFileHandler
这个Handler和RotatingFileHandler相似,不过,它没有经过判断文件大小来决定什么时候从新建立日志文件,而是间隔必定时间就 自动建立新的日志文件。重命名的过程与RotatingFileHandler相似,不过新的文件不是附加数字,而是当前时间。它的构造函数是:
TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
其中filename参数和backupCount参数和RotatingFileHandler具备相同的意义。
interval是时间间隔。
when参数是一个字符串。表示时间间隔的单位,不区分大小写。它有如下取值:
S 秒
M 分
H 小时
D 天
W 每星期(interval==0时表明星期一)
midnight 天天凌晨
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
|
import
logging
#create logger
logger
=
logging.getLogger(
'TEST-LOG'
)
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch
=
logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create file handler and set level to warning
fh
=
logging.FileHandler(
"access.log"
)
fh.setLevel(logging.WARNING)
# create formatter
formatter
=
logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# add formatter to ch and fh
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add ch and fh to logger
logger.addHandler(ch)
logger.addHandler(fh)
# 'application' code
logger.debug(
'debug message'
)
logger.info(
'info message'
)
logger.warn(
'warn message'
)
logger.error(
'error message'
)
logger.critical(
'critical message'
)
|
文件自动截断例子
1 import logging 2 3 from logging import handlers 4 5 logger = logging.getLogger(__name__) 6 7 log_file = "timelog.log" 8 #fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3) 9 fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3) 10 11 12 formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s') 13 14 fh.setFormatter(formatter) 15 16 logger.addHandler(fh) 17 18 19 logger.warning("test1") 20 logger.warning("test12") 21 logger.warning("test13") 22 logger.warning("test14") 23 复制代码
经常使用正则表达式符号
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
'.'
默认匹配除\n以外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
'^'
匹配字符开头,若指定flags MULTILINE,这种也能够匹配上(r
"^a"
,
"\nabc\neee"
,flags
=
re.MULTILINE)
'$'
匹配字符结尾,或e.search(
"foo$"
,
"bfoo\nsdfsf"
,flags
=
re.MULTILINE).group()也能够
'*'
匹配
*
号前的字符
0
次或屡次,re.findall(
"ab*"
,
"cabb3abcbbac"
) 结果为[
'abb'
,
'ab'
,
'a'
]
'+'
匹配前一个字符
1
次或屡次,re.findall(
"ab+"
,
"ab+cd+abb+bba"
) 结果[
'ab'
,
'abb'
]
'?'
匹配前一个字符
1
次或
0
次
'{m}'
匹配前一个字符m次
'{n,m}'
匹配前一个字符n到m次,re.findall(
"ab{1,3}"
,
"abb abc abbcbbb"
) 结果
'abb'
,
'ab'
,
'abb'
]
'|'
匹配|左或|右的字符,re.search(
"abc|ABC"
,
"ABCBabcCD"
).group() 结果
'ABC'
'(...)'
分组匹配,re.search(
"(abc){2}a(123|456)c"
,
"abcabca456c"
).group() 结果 abcabca456c
'\A'
只从字符开头匹配,re.search(
"\Aabc"
,
"alexabc"
) 是匹配不到的
'\Z'
匹配字符结尾,同$
'\d'
匹配数字
0
-
9
'\D'
匹配非数字
'\w'
匹配[A
-
Za
-
z0
-
9
]
'\W'
匹配非[A
-
Za
-
z0
-
9
]
's'
匹配空白字符、\t、\n、\r , re.search(
"\s+"
,
"ab\tc1\n3"
).group() 结果
'\t'
'(?P<name>...)'
分组匹配 re.search(
"(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})"
,
"371481199306143242"
).groupdict(
"city"
) 结果{
'province'
:
'3714'
,
'city'
:
'81'
,
'birthday'
:
'1993'
}
|
最经常使用的匹配语法
1
2
3
4
5
|
re.match 从头开始匹配
re.search 匹配包含
re.findall 把全部匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符当作列表分隔符
re.sub 匹配字符并替换
|
反斜杠的困扰
与大多数编程语言相同,正则表达式里使用"\"做为转义字符,这就可能形成反斜杠困扰。假如你须要匹配文本中的字符"\",那么使用编程语言表示的正则表达式里将须要4个反斜杠"\\\\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可使用r"\\"表示。一样,匹配一个数字的"\\d"能够写成r"\d"。有了原生字符串,你不再用担忧是否是漏写了反斜杠,写出来的表达式也更直观。
仅需轻轻知道的几个匹配模式
1
2
3
|
re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)
M(MULTILINE): 多行模式,改变
'^'
和
'$'
的行为(参见上图)
S(DOTALL): 点任意匹配模式,改变
'.'
的行为
|