异常处理
- 形式
try:
正常操作
except:
发生异常,执行这块代码
else:
如果没有异常,执行这块代码
finally:
不管如何都执行这块代码
- 例子(除数不能为零)
try:
print('try...')
r = 10 / 0
print('result:', r)
except ZeroDivisionError as e:
print('except:', e)
finally:
print('finally...')
print('END')
输出:
try...
except: division by zero
finally...
END
从输出可以看到,当错误发生时,后续语句print('result:', r)不会被执行,except由于捕获到ZeroDivisionError,因此被执行。最后,finally语句被执行。然后,程序继续按照流程往下走。
- 抛出异常
python使用raise语句抛出一个指定异常。
>>> raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception
从结果看出,raise Exception
引发了一个没有相关错误信息的普通异常 python内部常见的异常类有:
异常名称 | 描述 |
---|---|
Exception | 常规错误的基类 |
AttributeError | 对象没有这个属性 |
IOError | 输入/输出操作失败 |
IndexError | 序列中没有此索引 |
KeyError | 映射中没有这个键 |
NameError | 未声明对象 |
SyntaxError | 语法错误 |
SystemError | 一般解释器系统错误 |
ValueError | 传入无效的参数 |
time模块
- 时间的格式化符号
格式 | 含义 |
---|---|
%d | 一个月中的第几天 |
%H | 一天中的第几个小时 |
%I | 第几个小时,12小时制 |
%j | 一年中的第几天 |
%m | 月份 |
%M | 分钟数00-59 |
%S | 秒 |
%w | 一星期的第几天 |
%Y | 完整的年份 |
- 导入模块
import time
,常用的函数有:- time()函数,返回当前时间的时间戳,语法是:time.time()
>>> import time >>> time.time() 1522808629.3103108
- localtime()函数格式化时间戳为本地时间,语法:time.localtime([secs]),如果secs参数没有传入,就以当前时间为转换标准
>>> time.localtime() time.struct_time(tm_year=2018, tm_mon=4, tm_mday=4, tm_hour=10, tm_min=25, tm_sec=49, tm_wday=2, tm_yday=94, tm_isdst=0)
- mktime(t)函数,执行与localtime()的相反操作,t是一个元组
- sleep(secs)函数,用于推迟调用线程的运行,可通过参数secs指定进程挂起的时间
time.sleep(3)
- strftime(format[,t])函数用于接收时间元组,返回以可读的字符表示的当地时间,参数是时间的格式
>>> time.strftime("%Y-%m-%d %H:%M:%S") '2018-04-04 10:43:35'
datetime模块
- datetime模块有5个类
- datetime.date 表示日期的类,属性有year,month,day
- datetime.time 表示时间的类,属性有hour,minute,second,microsecond
- datetime.datetime 表示日期时间
- datetime.timedelta 表示时间间隔,即两个时间之间的长度
- datetime.tzinfo 与时区有关的相关信息
其中,datetime.datetime类用的最为普遍。 - 看一下datetime.datetime这个类有哪些方法:
>>> import datetime >>> dir(datetime.datetime) ['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year'
- datetime.datetime常用方法:
- today()返回一个表示当前本地时间的datetime对象
>>> import datetime >>> datetime.datetime.today() datetime.datetime(2018, 4, 4, 11, 15, 36, 421226) >>> t = datetime.datetime.today() >>> print(t) 2018-04-04 11:15:58.517497
- now([tz]),可选参数tz表示时区
>>> t = datetime.datetime.now() >>> print(t) 2018-04-04 11:17:55.784348
- strftime(format) 将格式字符串转换为datetime对象
>>> dt = datetime.datetime.today() >>> t = dt.strftime("%Y-%m-%d %H:%M:%S") >>> print(t) 2018-04-04 11:20:55
- datetime.timedelta()计算昨天的时间
>>> delta = datetime.now() + timedelta(days=-1)
>>> print(delta)
2018-04-03 11:26:37.624064
os模块
执行系统常用命令可以用os模块
- os模块的可用方法有:
['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']
-
常用的方法
- os.name 显示你正在使用的平台,windows是nt,linux是pofix
>>> import os >>> os.name 'posix'
- os.system(cmd)用来运行shell命令
linux下
>>> os.system("pwd") /root 0
windows下:
os.system('ipconfig')
输出乱码:
Windows IP ���� ��̫�������� ��������: �����ض��� DNS �� . . . . . . . : �������� IPv6 ��ַ. . . . . . . . : fe80::ccf6:ca07:5cf4:5c8d%9 IPv4 ��ַ . . . . . . . . . . . . : 10.148.60.71 �������� . . . . . . . . . . . . : 255.255.255.0 Ĭ������. . . . . . . . . . . . . : 10.148.60.1
解决方法:
>>>a = os.popen('ipconfig | findstr IPv4') >>>print(a.read()) IPv4 地址 . . . . . . . . . . . . : 10.148.60.71 IPv4 地址 . . . . . . . . . . . . : 192.168.59.1 IPv4 地址 . . . . . . . . . . . . : 192.168.42.1
windows的默认编码是gbk,而python是utf8
- os.getcwd()打印当前工作目录
>>> os.getcwd() '/root'
- os.chdir()改变工作目录
os.chdir('/tmp') os.getcwd() '/tmp'
- os.listdir(path)返回指定目录下的所有文件和目录名,返回一个列表,可以用来循环遍历所有文件和目录
>>> os.listdir('/home') ['user_09', 'user_04', 'user_06', 'user_01', 'user_07', 'user_08', 'user_05', 'user_00', 'greenfish', 'user_02', 'text', 'user_03']
- os.remove(path)函数用来删除一个文件。不能用来删除目录
- os.mkdir()创建目录,但只能创建单层目录,否则会报错
>>> os.mkdir('/tmp/d1') >>> os.mkdir('/tmp/d1/d2/d3') Traceback (most recent call last): File "<stdin>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: '/tmp/d1/d2/d3'
- os.makedirs() 方法用于递归创建目录。类似于linux里mkdir的-p选项
>>> os.makedirs('/tmp/d1/d2/d3') >>>
- os.path的常用方法:
- os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。
- os.path.exists()函数用来检验给出的路径是否真地存在
- os.path.split(path):将path分割成目录和文件名二元组返回。
>>> os.path.split('/etc/samba') ('/etc', 'samba')
- os.path.splitext():分离文件名与扩展名
>>> os.path.splitext('/etc/samba/smb.conf') ('/etc/samba/smb', '.conf')
- os.path.join(path,name):连接目录与文件名或目录
>>> os.path.join('/etc','new') '/etc/new'
- os.path.basename(path):返回文件名
- os.path.dirname(path):返回文件路径
- 利用os.path列出当前目录下的所有目录
[x for x in os.listdir() if os.path.isdir(x)]
- 列出当前目录下的所有.py文件
>>> [x for x in os.listdir() if os.path.isfile(x) and os.path.splitext(x)[1]=='.py'] ['abcd.py', 'login.py', 'nine.py', 'count.py', 'fact.py', 'string_count.py']
subprocess模块
- 执行命令,并显示,只要记住以下用法:
import subprocess
status,result = subprocess.getstatusoutput('dir')
if status == 0:
print(result)
status为0,表示执行成功,成功就显示result
输出:
C:\Users\Administrator\Anaconda3\python.exe E:/pythonproject2018/demon1.py
驱动器 E 中的卷是 macos
卷的序列号是 C06B-1FE9
E:\pythonproject2018 的目录
2018/04/04 23:27 <DIR> .
2018/04/04 23:27 <DIR> ..
2018/04/04 23:24 <DIR> .idea
2018/04/04 23:27 229 demon1.py
1 个文件 229 字节
3 个目录 94,782,509,056 可用字节
在python2里面,有commands模块,而python3用的是以上模块
sys模块
-
sys模块提供了一系列有关Python运行环境的变量和函数。
-
常见用法:
- sys.argv 获取当前正在执行的命令行参数的参数列表(list)。
变量 解释 sys.argv[0] 当前程序名 sys.argv[1] 第一个参数 sys.argv[2] 第二个参数 #!/usr/bin/env python # coding:utf-8 import sys print(f"当前程序名是:{sys.argv[0]}") print(f"第一个参数是:{sys.argv[1]}") print(f"第二个参数是:{sys.argv[2]}") print(f"第三个参数是:{sys.argv[3]}")
执行结果:
[root@localhost tmp]# python argvs.py 1 2 3 当前程序名是:argvs.py 第一个参数是:1 第二个参数是:2 第三个参数是:3
- sys.stdout重定向,当我们在Python中打印对象调用print(obj)时候,事实上是调用了 sys.stdout.write(obj+'\n'),print将你需要的内容打印到了控制台,然后追加了一个换行符print 会调用 sys.stdout 的 write 方法
# 以下两个命令是等价的 sys.stdout.write('hello'+'\n') print('hello')
- 如果把文件的对象的引用赋给 sys.stdout,那么print调用的就是文件对象的 write 方法
# 执行完程序后,在当前目录下会有一个1.log文件,内容是hello,但是控制台中不会显示print中的内容 f = open('1.log', 'w') sys.stdout = f print('hello')
- sys.platform获取当前执行环境的平台,如win32表示是Windows32bit操作系统,linux2表示是linux平台;
>>> sys.platform 'linux'
random模块
- 该模块用于生成随机数
- 通常用法:
- random.random()用于生成0-1之间的随机数
>>> random.random() 0.30966666987870883
- random.ranint(1,10)随机生成指定范围内的整数
>>> random.randint(1,10) 8
- random.uniform(1,10)随机生成一个指定范围内的浮点数
>>> random.uniform(1,10) 3.356025185781945
- random.randrange(10,100,2)在[2,4,6....98]这个列表中随机取整数
>>> random.randrange(10,100,2) 20
- random.sample("string",number)在指定字符中随机取出指定个数的字符在一个列表中
>>> random.sample("asdfaopnn",4) ['d', 'f', 'a', 'n']
string模块
-
string模块主要用于对字符串进行操作。
-
常用方法:
- string.ascii_letters打印所有大小写英文字母
>>> string.ascii_letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
- string.hexdigits 十六进制
>>> string.hexdigits '0123456789abcdefABCDEF'
- string.digits 0-9数字
>>> string.digits '0123456789'
- string.ascii_uppercase和string.ascii_lowercase 分别输出大小写字母
- string.punctuation 特殊字符
>>> string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
- string.printable 所有符号
-
利用random和string模块,随机生成四位数验证码(包括数字字母)
#!/usr/bin/env python
# coding:utf-8
import random,string
string = string.ascii_letters + string.digits
l = str()
for i in random.sample(string,4):
l += i
print(l)
hashlib模块
- 用于加密相关的操作,代替了md5模块和sha模块,主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法。
- md5加密
hash = hashlib.md5()
hash.update('admin'.encode('utf-8'))
print(hash.hexdigest())
21232f297a57a5a743894a0e4a801fc3
也可以在初始化的时候再加密一层,如:
hash = hashlib.md5("test".encode("utf-8"))
hash.update("admin".encode("utf-8"))
print(hash.hexdigest())
9283a03246ef2dacdc21a9b137817ec1
两者的结果不一样
json模块
- json提供四个功能:dumps, dump, loads, load
- dumps,将数据通过特殊的形式转换为所有程序语言都认识的字符串
>>> import json
>>> data = ['aa', 'bb', 'cc']
>>> j_str = json.dumps(data)
>>> j_str
'["aa", "bb", "cc"]'
- loads,将json编码的字符串再转换为python的数据结构
>>> j_str
'["aa", "bb", "cc"]'
>>> mes = json.loads(j_str)
>>> mes
['aa', 'bb', 'cc']
- Python字典类型转换为json对象
data1 = {
'no' : 1,
'name' : 'Bill',
'url' : 'http://www.bill.com'
}
json_str = json.dumps(data1)
print ("Python 原始数据:", repr(data1))
print ("JSON 对象:", json_str)
- 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])
输出结果:
Python 原始数据: {'name': 'Bill', 'no': 1, 'url':'http://www.bill.com'}
JSON 对象: {"name": "Bill", "no": 1, "url": "http://www.bill.com"}
data2['name']: Bill
data2['url']: http://www.bill.com
- 如果你要处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据。例如:
# 写入 JSON 数据
with open('data.json', 'w') as f:
json.dump(data, f)
# 读取数据
with open('data.json', 'r') as f:
data = json.load(f)
-
Python 编码为 JSON 类型转换对应表:
Python JSON dict object list, tuple array str string int, float, int- & float-derived Enums number True true False false None null -
JSON 解码为 Python 类型转换对应表:
JSON Python object dict array list string str number (int) int number (real) float true True false False null None
nginx日志切割小实例
#!/usr/bin/env python
# coding:utf-8
import shutil
from datetime import datetime
class CutLog(object):
def __init__(self):
self.accesslog = 'access.log'
self.errorlog = 'error.log'
def getToday(self):
self.nowTime = datetime.now().strftime("%Y-%m-%d")
self.todayAccesslog = self.nowTime + self.accesslog
self.todayErrorlog = self.nowTime + self.errorlog
def logRename(self):
shutil.copy(self.accesslog,self.todayAccesslog)
shutil.copy(self.errorlog,self.todayErrorlog)
fa = open(self.accesslog,'w') # 文件以w模式打开然后关闭就等于清空了文件内容
fe = open(self.errorlog,'w')
fa.close()
fe.close()
def main():
cutlog = CutLog()
cutlog.getToday()
cutlog.logRename()
if __name__ == "__main__":
main()