模块,用一砣代码实现了某个功能的代码集合。
类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。
如:os 是系统相关的模块;file是文件操作相关的模块
模块分为三种:
1、定义模块
情景一:

情景二:

情景三:

2、导入模块
Python之所以应用越来越广泛,在一定程度上也依赖于其为程序员提供了大量的模块以供使用,如果想要使用模块,则需要导入。导入模块有一下几种方法:
1 2 3 4 | import modulefrom module.xx.xx import xxfrom module.xx.xx import xx as rename from module.xx.xx import * |
导入模块其实就是告诉Python解释器去解释那个py文件
那么问题来了,导入模块时是根据那个路径作为基准来进行的呢?即:sys.path
import sysprint sys.path[‘D:\\python\\s12\\day5\\note‘, ‘D:\\python‘, ‘C:\\Python35\\python35.zip‘, ‘C:\\Python35\\DLLs‘, ‘C:\\Python35\\lib‘, ‘C:\\Python35‘, ‘C:\\Python35\\lib\\site-packages‘]
如果sys.path路径列表没有你想要的路径,可以通过 sys.path.append(‘路径‘) 添加。
通过os模块可以获取各种目录,例如:

import sys import os pre_path = os.path.abspath(‘../‘) sys.path.append(pre_path)
一、下载安装
下载安装有两种方式:

yum pip apt-get ...

下载源码
解压源码
进入目录
编译源码 python setup.py build
安装源码 python setup.py install注:在使用源码安装时,需要使用到gcc编译和python开发环境,所以,需要先执行:
1 2 3 4 | yum install gccyum install python-devel或apt-get python-dev |
安装成功后,模块会自动安装到 sys.path 中的某个目录中,如:
1 | /usr/lib/python2.7/site-packages/ |
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 | #_*_coding:utf-8_*_import timeimport datetimeprint(time.clock()) #返回处理器时间,3.3开始已废弃print(time.process_time()) #返回处理器时间,3.3开始已废弃print(time.time()) #返回当前系统时间戳print(time.ctime()) #输出Tue Jan 26 18:23:48 2016 ,当前系统时间print(time.ctime(time.time()-86640)) #将时间戳转为字符串格式print(time.gmtime(time.time()-86640)) #将时间戳转换成struct_time格式print(time.localtime(time.time()-86640)) #将时间戳转换成struct_time格式,但返回 的本地时间print(time.mktime(time.localtime())) #与time.localtime()功能相反,将struct_time格式转回成时间戳格式#time.sleep(4) #sleepprint(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将struct_time格式转成指定的字符串格式print(time.strptime("2016-01-28","%Y-%m-%d") ) #将字符串格式转换成struct_time格式#datetime moduleprint(datetime.date.today()) #输出格式 2016-01-26print(datetime.date.fromtimestamp(time.time()-864400) ) #2016-01-16 将时间戳转成日期格式current_time = datetime.datetime.now() #print(current_time) #输出2016-01-26 19:04:30.335935print(current_time.timetuple()) #返回struct_time格式#datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])print(current_time.replace(2014,9,12)) #输出2014-09-12 19:06:24.074900,返回当前时间,但指定的值将被替换str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") #将字符串转换成日期格式new_date = datetime.datetime.now() + datetime.timedelta(days=10) #比现在加10天new_date = datetime.datetime.now() + datetime.timedelta(days=-10) #比现在减10天new_date = datetime.datetime.now() + datetime.timedelta(hours=-10) #比现在减10小时new_date = datetime.datetime.now() + datetime.timedelta(seconds=120) #比现在+120sprint(new_date) |
| 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 randomprint random.random()print random.randint(1,2)print random.randrange(1,10) |
生成随机验证码
1 2 3 4 5 6 7 8 9 10 | import randomcheckcode = ‘‘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下cdos.curdir 返回当前目录: (‘.‘)os.pardir 获取当前目录的父目录字符串名:(‘..‘)os.makedirs(‘dirname1/dirname2‘) 可生成多层递归目录os.removedirs(‘dirname1‘) 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推os.mkdir(‘dirname‘) 生成单级目录;相当于shell中mkdir dirnameos.rmdir(‘dirname‘) 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirnameos.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不存在,返回Falseos.path.isabs(path) 如果path是绝对路径,返回Trueos.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回Falseos.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回Falseos.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/bruceg/p/5199103.html