学习目录
异常处理
定义
导入方法
本质
优化
分类
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("暂停几秒, 执行")
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)
来源: http://www.bubuko.com/infodetail-2572873.html