Python基础之模块

  • 学习目录
  • 异常处理
  • 定义
  • 导入方法
  • 本质
  • 优化
  • 模块分类

0x01 异常处理

  • 格式
try:
	错误语句   
except:
	返回错误信息   
finally:
	无论对错,都要执行语句   
  • 除数不能为0
import json
def test():
	result = dict()
	try:
		print(2/0)
	except Exception as a:
		result["msg"] = "除数不能为零。"
		result["code"] = 403
		result["data"] = [{"a": 1}, {"b": 2}]
	finally:
		return jsondumps(result)
if __name__ == '__main__':
	print(test())

0x02 定义

  • 模块定义
    * 从逻辑上组织(变量、函数、类),本质是.py文件
  • 包定义
    * 从逻辑商组织模块,一个目录(带有__init__.py)文件

0x03 导入方法

  • 导入方法
    * 导入模块
    import module_name # 导入单个模块 import module_name1, module_name2 # 导入多个模块 from module_name import * # 导入所有(不推荐) from module_name import test as newtest # 别名 from module import 方法1,方法2 # 导入指定方法
    * 导入包
    import package
    * Exp 创建test.py文件
    name = Chow def hello(): print('Hello Python') def python(): print('Robin Chow')
    * Exp 导入test模块函数及方法
    ```
# 导入模块      
import test            # test即文件名      
# 调用模块变量       
print(test.name)       # name即文件变量         
# 导入方法   
print(test.hello())    # hello()即文件函数  
```

0x04 本质

  • import本质
    * 模块本质
    -- 把导入文件顺序执行
    * 包本质
    -- 执行该包下__init__.py文件
* 路径搜索       
```
# 查询顺序      
# import module_name  --> module_name.py  ---> module_name.py路劲  ---> sys.path    
```
* 搜索路径      


* Exp 把文件路径追加到python环境变量            
```
import sys, os
print(sys.path)
# 查找路径及文件绝对路径    
x = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.paht.insert(x)         # 插入环境变量路径列表    
```

0x05 优化

  < 待整理 >    

0x06 分类

   < 待整理 >

0x07 模块讲解

  • datatime模块
  • 导入模块

    from datatime import datetime,timedelta        
    print(datetime.now())
    
  • 方法

.now           # 获取当前时间      
.now().year    # 年   
.now().month   # 月   
.now().day     # 日    
.now().hour    # 时   
.now().minute  # 分   
.now().second  # 秒    
.now().microsecond  # 毫秒    
.now().strftime("%Y-%m-%d")  # 年-月-日   
  • datedelta 用法
    nowTime = datetime.now() nowTime += timedelta(hours =+ 3) print(nowTime)
  • 约定形式
    %Y # 十进制年 %m # 月 %d # 每月第几天 %H # 小时 %M # 分钟 %S # 秒数 %e # 标准时间 %a # 本地星期名称 %b # 本地简化月份 %d # 一月中第几天
  • time模块
    * 常用方法
    import time time.sleep(5) # 暂停5秒 time.time() # 时间戳,从1970-01-01到现在的时间 time.ctime() # 创建文件时间 time.localtime() # 把时间戳转换为struct time time.asctime([t]) # 把时间元组或struct time 标识为:'Sun Jun 23 06:43: 23 2018' print("暂停几秒,执行")
* 常用时间格式      
```
print(time.time())                      # 时间戳   
print(time.strftime("%Y-%m-%d %X"))     # 格式化字符串时间   
print(time.localtime())                 # 本地时区  
print(time.gmtime())                    # UTC时区   
```

* 时间戳转换为本地时间(localtime)   
```
newtime = time.time()                      # 时间戳   
print(newtime)
localtime = time.localtime(newtime)        # 时间戳转换为本地时间   
print(localtime)
```

* 本地时间转换为时间戳       
```
localtime = time.localtime(time.time())      # 本地时间   
print(localtime)
newtime = time.mktime(localtime)             # 本地时间转换为时间戳  
print(newtime)
```

* 本地时间转换字符串时间      
```
localtime = time.localtime(time.time())         # 本地时间   
print(localtime)
strtime = time.strftime("%Y-%m-%d",localtime)   # 本地时间转换为字符串时间   
print(strtime)
```

* 字符串时间 转换为 UTF时间     
```
strtime = "2018-04-24"                          # 字符串时间   
print(strtime)
utctime = time.strptime(strtime,"%Y-%m-%d")     # 字符串时间转换为UTC时间   
print(utctime)
```
  • commands模块
    * Linux下模块, 用于执行Linux命令
    ```
# getstatusoutput()返回状态码及值,成功返回状态为0,否则返回非0     
a = commands.getstatusoutput('ifconfig')    # 返回0及值   
a = commands.getstatusoutput('ipppconfig')  # 返回非0及值   
print(a) 
# getoutput()只返回状态码    
b = commands.getoutput('ifconfig')
print(b)
# win下使用   
import subprocess
result = subprocess.getoutput('ipconfig')
print(result)
```
  • os模块
    * 与系统交互的接口
    os.getcwd() # 获取工作目录,即当前脚本工作目录路径 os.chdir("目录") # 改变目录;相当于shell下cd os.curdir # 返回当前目录: ('.') os.pardir # 获取当前目录的父目录字符串名:('..') os.makedirs('目录1/目录2') # 生成递归目录 os.removedirs('目录1') # 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推 os.mkdir('目录') # 创建单级目录;相当于shell中mkdir dirname os.rmdir('目录') # 删除空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname os.listdir('目录') # 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印 os.remove() # 删除文件 os.rename("老文件/目录","新文件/目录") # 重命名文件/目录 os.stat('路径/文件') # 获取文件/目录信息 os.sep # 输出操作系统特定的路径分隔符,win为"\",Linux为"/" os.linesep # 输出当前平台使用的行终止符,win下为" ",Linux下为" " os.pathsep # 输出用于分割文件路径的字符串 win下为;,Linux下为: os.name # 输出字符串所在系统。win->'nt'; Linux->'posix' os.system("命令") # 执行命令,输出结果 os.popen("命令").read() # 执行命令,读取结果 os.environ # 获取系统环境变量 os.path.abspath(路径) # 返回path绝对路径 os.path.split(路径) # 将路径分割成目录和文件名 os.path.dirname(路径) # 返回路径目录 os.path.exists(路径) # 路径存在,返回True;路径不存在,返回False os.path.isabs(路径h) # 路径是绝对路径,返回True os.path.isfile(路径) # 路径是存在的文件,返回True。否则返回False os.path.isdir(路径) # 路径是存在的目录,则返回True。否则返回False os.path.join(路径1[, 路径2[, ...]]) # 将多个路径组合后返回 os.path.getatime(路径) # 返回路径所指向的文件或者目录的最后访问时间 os.path.getmtime(路径) # 返回路径所指向的文件或者目录的最后修改时间 os.path.getsize(路径) # 返回路径大小
  • sys模块
    * 系统与python解释器交互接口
    sys.argv # 命令行参数List,第一个元素是程序本身路径 sys.exit(n) # 退出程序,正常退出时exit(0),错误退出sys.exit(1) sys.version # 获取Python解释程序的版本信息 sys.path # 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 sys.platform # 返回操作系统平台名称
原文地址:https://www.cnblogs.com/RobinChow/p/8878797.html