Python常用模块

Python之常用模块

模块,用一砣代码实现了某个功能的代码集合。 

类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。

如:os 是系统相关的模块;file是文件操作相关的模块

模块分为三种:

  • 自定义模块
  • 内置模块
  • 开源模块
自定义模块

1、定义模块

情景一:

  

情景二:

  

情景三:

  

2、导入模块

Python之所以应用越来越广泛,在一定程度上也依赖于其为程序员提供了大量的模块以供使用,如果想要使用模块,则需要导入。导入模块有一下几种方法:

1
2
3
4
import module
from module.xx.xx import xx
from module.xx.xx import xx as rename 
from module.xx.xx import *

导入模块其实就是告诉Python解释器去解释那个py文件

  • 导入一个py文件,解释器解释该py文件
  • 导入一个包,解释器解释该包下的 __init__.py 文件
开源模块

一、下载安装

下载安装有两种方式:

方式一
方式二
注:在使用源码安装时,需要使用到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/

二、导入模块

同自定义模块中导入的方式

三、模块 paramiko

paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。

1、下载安装

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检查是否安装成功

2、使用模块

执行命令 - 通过用户名和密码连接服务器
执行命令 - 过密钥链接服务器
上传或者下载文件 - 通过用户名和密码
上传或下载文件 - 通过密钥
内置模块

 

time & datetime模块

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
import time
import datetime
 
time
print(time.clock())  #返回处理器时间,3.3以后废弃 4.444098792316153e-07
print(time.process_time()) #返回处理器时间 0.031200199999999997
print(time.time())     #返回当前系统时间戳 1463472071.3892002
print(time.ctime())    #返回当前系统时间 Tue May 17 16:01:11 2016
print(time.ctime(time.time()-86400))   #转换成字符串格式 Mon May 16 16:01:11 2016
print(time.gmtime(time.time()-86400))  #将时间戳转换成struct_time格式 time.struct_time(tm_year=2016, tm_mon=5, tm_mday=16, tm_hour=8, tm_min=1, tm_sec=11, tm_wday=0, tm_yday=137, tm_isdst=0)
print(time.localtime(time.time()-86400))  #将时间戳转换成struct_time格式,本地时间。 time.struct_time(tm_year=2016, tm_mon=5, tm_mday=16, tm_hour=16, tm_min=13, tm_sec=25, tm_wday=0, tm_yday=137, tm_isdst=0)
print(time.mktime(time.localtime()))  #与time.localtime()功能相反,将struct_time格式转回成时间戳格式  1463472904.0
time.sleep(4#sleep 每隔四秒以执行
print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将struct_time格式转成指定的字符串格式  2016-05-17 08:16:22
 
datetime
print(datetime.date.today()) #输出格式 2016-05-17
print(datetime.date.fromtimestamp(time.time()-86400) ) # 将时间戳转成日期格式 2016-05-16
current_time = datetime.datetime.now() #
print(current_time) #输出2016-05-17 16:17:59.863200
print(current_time.timetuple()) #返回struct_time格式  time.struct_time(tm_year=2016, tm_mon=5, tm_mday=17, tm_hour=16, tm_min=17, tm_sec=59, tm_wday=1, tm_yday=138, tm_isdst=-1)
 
#datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
print(current_time.replace(2016,5,17)) #输出2016-05-17 16:19:33.753200,返回当前时间,但指定的值将被替换
 
str_to_date = datetime.datetime.strptime("21/11/06 16:30""%d/%m/%y %H:%M"#将字符串转换成日期格式
new_date1 = datetime.datetime.now() + datetime.timedelta(days=10#比现在加10天 2016-05-27 16:21:16.279200
new_date2 = datetime.datetime.now() + datetime.timedelta(days=-10#比现在减10天 2016-05-07 16:21:44.459200
new_date3 = datetime.datetime.now() + datetime.timedelta(hours=-10#比现在减10小时 2016-05-17 06:22:01.299200
new_date4 = datetime.datetime.now() + datetime.timedelta(seconds=120#比现在+120s 2016-05-17 16:24:10.917200
new_date5 = datetime.datetime.now() + datetime.timedelta(weeks=20#比现在+10周 2016-10-04 16:23:02.904200
print(new_date5)
DirectiveMeaningNotes
%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.

random模块

随机数

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
11
import  random
tmp = ""
for in range(6):
    rad1 = random.randrange(4)
    if rad1 ==1 or rad1 ==3:
        rad2 = random.randrange(0,9)
        tmp += str(rad2)
    else:
        rad3 = random.randrange(65,90)
        tmp += chr(rad3)
print(tmp)

sys模块

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
import sys
import time
print(sys.argv)    #['C:/Users/Administrator/PycharmProjects/zyl/day-6/datetime,time模块/SYS.PY.py']
 
print(sys.path)    #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
 
print(exit())   #退出程序,正常退出时exit(0)
 
print(sys.version)  #3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]
 
print(sys.maxsize)   #9223372036854775807  最大的Int值
 
print(sys.platform)  #win32       操作系统类型
 
 
####################################安装包流程不换行显示##################################
for  in range(31):
    sys.stdout.write(" ")         #清空当前数据网上叠加
    sys.stdout.write("%s%% | %s " %(int(i/30*100),int(i/30*100)*"#"))
    sys.stdout.flush()
    time.sleep(0.3)
 
####################################安装流程换行显示####################################
 
for in range(101):
    sys.stdout.write(" ")
    sys.stdout.write("%s%% | %s " %(i,i*"#"))
    sys.stdout.flush()
    time.sleep(0.1)

 

json & pickle 模块

用于序列化的两个模块

  • json,用于字符串 和 python数据类型间进行转换
  • pickle,用于python特有的类型 和 python的数据类型间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

pickle 购物实例

(后续更新中.....)

 

原文地址:https://www.cnblogs.com/Leo_wl/p/5503959.html