本站以分享各种运维经验和运维所需要的技能为主
《python零基础入门》:python零基础入门学习
《python运维脚本》: python运维脚本实践
《shell》:shell学习
《terraform》持续更新中:terraform_Aws学习零基础入门到最佳实战
《k8》暂未更新
《docker学习》暂未更新
《ceph学习》ceph日常问题解决分享
《日志收集》ELK+各种中间件
《运维日常》运维日常
《linux》运维面试100问
时间表示方法和异常处理
时间表示方法:
time模块:
时间表示方法:
-
时间戳:自1970-1-1 0:0:0到某一时间之间的秒数
-
UTC时间,世界协调时.
-
struct_time元组:9个元素组成:(年月日时分秒,一周中第几天,一年中的第几天,是否是夏季节约时间--原来时间-1)
闰秒---- 61
>>> import time
#获取当时的时间戳
>>> time.time()
1575854726.0655887 -----1970--至今
#获取UTC的字符串形式时间
>>> time.ctime()
'Mon Dec 9 09:26:30 2019'
#获取当前时间的9元组
>>> time.localtime()
time.struct_time(tm_year=2019, tm_mon=12, tm_mday=9, tm_hour=9, tm_min=27, tm_sec=2, tm_wday=0, tm_yday=343, tm_isdst=0)
>>> t = time.localtime()
>>> t.tm_year
2019
>>> t.tm_yday
343
#算数计时器:
import time
result = 0
start = time.time()
for i in range(1,10000001):
result += i
end = time.time()
print(result)
print(end - start)
#睡眠3秒
>>> import time
>>> time.sleep(3)
#返回特定的时间格式
>>> time.strftime('%Y-%m-%d %H:%M:%S')
'2019-12-09 09:48:38'
>>> time.strftime('%a %A')
'Mon Monday'
#把时间字符串转化为9元素组格式
>>> t = time.strptime('2019-12-09 09:48:38', '%Y-%m-%d %H:%M:%S')
>>> t.tm_year
2019
>>> time.strptime('2019-12-09 09:48:38', '%Y-%m-%d %H:%M:%S')
time.struct_time(tm_year=2019, tm_mon=12, tm_mday=9, tm_hour=9, tm_min=48, tm_sec=38, tm_wday=0, tm_yday=343, tm_isdst=-1)
#应用
import time
t9 = time.strptime('2019-12-09 09:00:00', '%Y-%m-%d %H:%M:%S')
t12 = time.strptime('2019-12-09 12:00:00', '%Y-%m-%d %H:%M:%S')
with open('mylog.txt') as fobj:
for line in fobj:
t = time.strptime(line[:19],'%Y-%m-%d %H:%M:%S')
if t > t12 :
break
if t >=t9:
print(line,end='')
# with open('mylog.txt') as fobj:
# for line in fobj:
# t = time.strptime(line[:19],'%Y-%m-%d %H:%M:%S')
# if t9 <= t <= t12 :
# print(line,end='')
datetime模块:
简单应用:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2019, 12, 9, 10, 48, 9, 388722)
>>> t.year
2019
>>> t.month
12
>>> t.day
9
>>> t.min
t.min t.minute
>>> t.minute
48
>>> t.hour
10
>>> t.second
52
>>> t.microsecond
887151
>>> t9 = datetime.strptime('2019-12-9 10:55:29' , '%Y-%m-%d %H:%M:%S') #指定字符串转成datetime对象
>>> t9
datetime.datetime(2019, 12, 9, 10, 55, 29)
>>> t = datetime.now()
>>> t
datetime.datetime(2019, 12, 9, 10, 55, 29, 493483)
>>> t.strftime('%Y/%m/%d %H:%M:%S') #datetime对象转成指定字符串
'2019/12/09 10:55:29'
案例一:
from datetime import datetime
t9 = datetime.strptime('2019-12-09 09:00:00', '%Y-%m-%d %H:%M:%S')
t12 = datetime.strptime('2019-12-09 12:00:00', '%Y-%m-%d %H:%M:%S')
with open('mylog.txt') as fobj:
for line in fobj:
t = datetime.strptime(line[:19],'%Y-%m-%d %H:%M:%S')
if t > t12 :
break
if t >=t9:
print(line,end='')
案例二:
# 计算时间差,获取从现在开始前100天,后100天
>>> from datetime import datetime,timedelta
>>> t = datetime.now()
>>> dats = timedelta(days=100,hours=1)
>>> t
datetime.datetime(2019, 12, 9, 11, 22, 46, 973981)
>>> t - dats
datetime.datetime(2019, 8, 31, 10, 22, 46, 973981)
>>> t + dats
datetime.datetime(2020, 3, 18, 12, 22, 46, 973981)
异常处理:
-
- 没有异常处理的代码,当程序遇到错误时,程序将会崩溃,终止执行,在屏幕上打印报错信息
-
- 异常处理是,提前考虑到程序运行过程中将会出现的错误,给出这些错误的解决方案,使得程序不要崩溃,还可以继续执行下去
try:
num = int(input('number: '))
result = 100 / num
print(result)
print('Done')
except (ValueError, ZeroDivisionError) as e:
print('无效输入',e)
except (EOFError, KeyboardInterrupt) :
print('\nBye-Bye')
#0 报错不能作为除数: ZeroDivisionError: division by zero
# asdasd 值不对类型 : ValueError: invalid literal for int() with base 10: 'asdasdasd'
# Ctrl D 直接结束: EOFError: EOF when reading a line
# >>> asdasdasd 直接Ctrl C----->结果:KeyboardInterrupt
#>>> a = [1 , 2 ]
#>>> a[3] 下标没有这个索引,只有0 1 --->IndexError: list index out of range
#>>> b 还没有定义变量b: ----->NameError: name 'b' is not defined
try:
num = int(input('number: '))
result = 100 / num
except (ValueError, ZeroDivisionError) as e:
print('无效输入',e)
except (EOFError, KeyboardInterrupt) :
print('\nBye-Bye')
exit(1) #程序遇到exit将会彻底结束,并且返回1,正确输出
else:
print(result) #前面的代码正确执行的时候,才执行
finally:
print('一定要执行的语句')
print('Done')
触发异常:
def set_age(name,age):
if not 0 < age < 120:
raise ValueError('年龄超出正常范围')
print('%s is %s years old' % (name,age))
if __name__ == '__main__':
set_age('牛老师',200)
import myerror
#调用上面的函数:
try:
name = input('名字: ')
age = int(input('年龄: '))
myerror.set_age(name,age)
except ValueError :
print('请输入0~120的年龄')
except (EOFError, KeyboardInterrupt) :
print('\nBye-Bye')
断言:
• 断言是一句必须等价于布尔值为真的判定
• 此外,发生异常也意味着表达式为假
def set_age(name,age):
assert 0 < age < 120,'年龄超出正常范围'
print('%s is %s years old' % (name,age))
if __name__ == '__main__':
try:
age = int(input('年龄: '))
set_age('牛牛',age)
except (ValueError,AssertionError) as e:
print('错误:',e)
except (KeyboardInterrupt,EOFError):
print('\nBye-Bye')
OS模块:
import os
os.getcwd() #pwd
os.listdir() #ls
os.mkdir('/root/dd') #mkdir
os.makedirs('/root/dd/ss/ss/ss') #mkdir -p
os.chdir() #cd
os.remove() #rm -rf
os.symlink('/etc/passwd','mimo') # ln -s
os.chmod('zhuji',0o755) # chmod 755 zhuji
#注意:linux命令chmod使用的进制为 8进制
>>> 0o755
493
os.chmod('zhuji',493) #十进制
os.stat('zhuji') #文件的详细信息,什么时候被改动或者被访问
#访问时间
#更改change时间:指定内容更改
#更改modify时间:内容以及权限都算在内
>>> os.stat('sss.py')
os.stat_result(st_mode=33188, st_ino=6426766, st_dev=2050, st_nlink=1, st_uid=0, st_gid=0, st_size=4, st_atime=1575875055, st_mtime=1575875055, st_ctime=1575875055)
>>> import time
>>> time.ctime(1575875055)
'Mon Dec 9 15:04:15 2019'
>>> sss = os.stat('sss.py')
>>> sss.st_atime
1575875055.8465357
>>> sss.st_size
4
判断:
os.path.isabs('/etc') #是绝对路径吗?
os.path.isdir('/asdf') #/asdf不存在也返回Ture
---修改一下os.path.isabs('/asdf')
os.path.isfile() #存在并且是文件吗? [ -f fname ]
os.path.ismount() #存在并且是挂载点吗?
os.path.isdir() #存在并且是目录吗? [ -d dname ]
os.path.islink() #存在并且是软链接吗?
os.path.exists() #存在吗? [ -e d/fname ]
>>> path = '/root/nsd1907/py02/day01/sss.txt'
>>> os.path.split(path)
('/root/nsd1907/py02/day01', 'sss.txt')
>>> os.path.basename(path)
'sss.txt'
>>> os.path.dirname(path)
'/root/nsd1907/py02/day01'
>>> os.path.join('/root/nsd1907/py02/day01','sss.txt')
'/root/nsd1907/py02/day01/sss.txt'
import shutil
shutil.copy('/etc/hosts','zhuji')#拷贝到当前
shutil.copytree() #拷贝目录
案例之遍历linux系统的目录:
# 递归列出目录中所有内容
>>> list(os.walk('anquan'))
[('anquan', ['console.apps', 'console.perms.d', 'limits.d', 'namespace.d'], ['access.conf', 'chroot.conf', 'console.handlers', 'console.perms', 'group.conf', 'limits.conf', 'namespace.conf', 'namespace.init', 'opasswd', 'pam_env.conf', 'sepermit.conf', 'time.conf', 'pwquality.conf']), ('anquan/console.apps', [], ['config-util', 'xserver', 'liveinst', 'setup']), ('anquan/console.perms.d', [], []), ('anquan/limits.d', [], ['20-nproc.conf']), ('anquan/namespace.d', [], [])]
>>> data = list(os.walk('anquan')) # 列表由5个元组构成
>>> len(data)
5
# 构成列表的元组有统一的结构:(字符串,列表,列表)
# 进一步观察元组结构:(路径字符串,该路径下目录列表,该路径下文件列表)
>>> data[0]
('anquan', ['console.apps', 'console.perms.d', 'limits.d', 'namespace.d'], ['access.conf', 'chroot.conf', 'console.handlers', 'console.perms', 'group.conf', 'limits.conf', 'namespace.conf', 'namespace.init', 'opasswd', 'pam_env.conf', 'sepermit.conf', 'time.conf', 'pwquality.conf'])
>>> data[1]
('anquan/console.apps', [], ['config-util', 'xserver', 'liveinst', 'setup'])
>>> data[2]
('anquan/console.perms.d', [], [])
# 遍历,打印5行元组
>>> for item in os.walk('anquan'):
... print(item)
# 遍历,将元组中的三项分别赋值给3个变量
>>> for path, folders, files in os.walk('anquan'):
... print(path, folders, files)
# 遍历,将目录列表和文件列表也逐一遍历出来
>>> for path, folders, files in os.walk('anquan'):
... print('%s:' % path)
... for mulu in folders:
... print(mulu, end='\t')
print('')
... for file in files:
... print(file, end='\t')
... print('\n')
pickle模块:
- 可以将任意的数据类型写到文件,还可以无损地取出
>>> import pickle
>>> shopping_list = ['apple','banana','egg','orange']
#将列表写入文件
>>> with open('/tmp/shopping.data' , 'wb') as fobj :
... pickle.dump(shopping_list,fobj)
...
#在文件中将列表取出
>>> with open('/tmp/shopping.data' , 'rb') as fobj :
... alist = pickle.load(fobj)
...
>>> type(alist)
<class 'list'>
>>> alist
['apple', 'banana', 'egg', 'orange']
>>>
案例练习:
记账程序:
import pickle
import os
from time import strftime
def save(fname):
'记录收入'
date = strftime('%Y-%m-%d')
try:
amount = int(input('金额: '))
comment = input('备注: ')
except ValueError:
print('输入的金额无效')
return
except (KeyboardInterrupt,EOFError):
print('\nbye')
exit(1)
# 在fname文件中取出最新余额,加上当前收入金额,即为最新余额
with open(fname,'rb') as fobj:
records = pickle.load(fobj)
balance = records[-1][-2] + amount
#将最新记录添加到文件中
record = [date, amount, 0, balance, comment]
records.append(record)
with open(fname,'wb') as fobj:
pickle.dump(records, fobj)
def cost(fname):
'记录支出'
date = strftime('%Y-%m-%d')
try:
amount = int(input('金额: '))
comment = input('备注: ')
except ValueError:
print('输入的金额无效')
return
except (KeyboardInterrupt,EOFError):
print('\nbye')
exit(1)
# 在fname文件中取出最新余额,减去当前支出金额,即为最新余额
with open(fname,'rb') as fobj:
records = pickle.load(fobj)
balance = records[-1][-2] - amount
#将最新记录添加到文件中
record = [date, 0, amount, balance, comment]
records.append(record)
with open(fname,'wb') as fobj:
pickle.dump(records, fobj)
def query(fname):
'查询'
#打印表头
print('%-12s%-8s%-8s%-12s%-20s' % ('date','save','cost','balance','comment'))
#取出全部记录:
with open(fname , 'rb') as fobj:
records = pickle.load(fobj)
#打印记录
for record in records:
print('%-12s%-8s%-8s%-12s%-20s' % tuple(record))
def show_menu():
cmds = {'0':save,'1':cost,'2':query}
menu = """(0) 收入
(1) 支出
(2) 查询
(3) 退出
请选择(0/1/2/3): """
fname = 'account.data'
init_data = [
['2019-12-10',0,0,10000,'init data']
]
#如果文件不存在,则创建并且写入初始化数据
if not os.path.exists(fname):
with open(fname,'wb') as fobj:
pickle.dump(init_data,fobj)
while 1:
try:
choice = input(menu).strip()
except (EOFError, KeyboardInterrupt):
choice = '3'
# except KeyError:
# print('无效输入:')
# continue
# except ValueError:
# print('请按照提示数字输入,谢谢')
if choice not in ['0','1','2','3']:
print('无效输入,请根据提示数字输入,谢谢')
continue
if choice == '3' :
print('bye-bye')
break
cmds[choice](fname)
if __name__ == '__main__':
show_menu()