第13次全天课笔记 20181021 异常
20181021
#代码统计工具
1 通过参数指定一个绝对路径,sys.argv
2 如果是文件,就直接统计文件的行数,并打印结果
3 判断一下是否为目录,就遍历,统计
找到这个目录下所有的文件,用os.walk可以找到,拼成绝对路径。
规则:
一种是开头是#encoding #-*-
还有一种是''' 或者""",判断某几行是'''或者"""开头,并且是'''或者"""
结尾
空行
两个变量:一个是统计当前文件的行数,还有累计行数
每个文件的路径和代码行,我想到存到字典
import os
import sys
import os.path
#for i in sys.argv:
# print (i)
def count_file_lines(file_path):
line_count = 0
flag =True
try:
fp = open(file_path,"r",encoding="utf-8")
encoding_type="utf-8"
fp.close()
except:
encoding_type="gbk"
with open(file_path,"r",encoding=encoding_type) as fp:
for line in fp:
if line.strip() == "":
continue
else:
if line.strip().endswith("'''") and flag == False:
flag = True
continue
if line.strip().endswith('"""') and flag == False:
flag = True
continue
if flag == False:
continue
if line.strip().startswith("#encoding") \
or line.strip().startswith("#-*-"):
line_count += 1
elif line.strip().startswith('"""') and line.strip().endswith('"""') and line.strip() != '"""':
continue
elif line.strip().startswith("'''") and line.strip().endswith("'''") and line.strip() != "'''":
continue
elif line.strip().startswith("#"):
continue
elif line.strip().startswith("'''") and flag == True:
flag = False
continue
elif line.strip().startswith('"""') and flag == True:
flag = False
continue
else:
line_count += 1
return line_count
def count_code_lines(path,file_types=[]):
if not os.path.exists(path):
print("您输入的目录或者文件路径不存在")
return 0
line_count =0
file_lines_dict ={}
if os.path.isfile(path):
#print("path:",path)
file_type = os.path.splitext(path)[1][1:]
#print(file_type)
#print (file_type in file_types)
if len(file_types)==0:
file_types=["py","cpp","c","java","ruby","ini","go","html","css","js","txt","vbs","php","asp","sh"]
if file_type in file_types:
line_count=count_file_lines(path)
return line_count
else:
file_path = []
for root, dirs,files in os.walk(path):
for file in files:
file_path.append(os.path.join(root,file))
for f in file_path:
file_type = os.path.splitext(f)[1][1:]
if len(file_types)==0:
file_types=["py","cpp","c","java","ruby","ini","go","html","css","js","txt","vbs","php","asp","sh"]
if file_type not in file_types:
continue
print (f)
line_num=count_file_lines(f)
line_count+=line_num
file_lines_dict[f]= line_num
return line_count,file_lines_dict
if __name__ == "__main__":
print (sys.argv)
if len(sys.argv) <2:
print ("请输入待统计行数的代码绝对路径!")
sys.exit()
count_path = sys.argv[1]
file_types = []
if len(sys.argv) >2:
for i in sys.argv[2:]:
file_types.append(i)
print (count_path,file_types)
#print(count_code_lines(count_path,file_types))
print(count_file_lines("e:\\b.py"))
测试的文件a.py:
#encoding=utf-8
import a
"""sddsdsf"""
'''sdfdsfd'''
'''sddsfds
sdfdsf
sdfdsf
sdfdss'''
"""sddsfds
sdfdsf
sdfdsf
sdfdss"""
print(1)
print(1)
print(1)
杜拉拉升职记
专访雷果国:从1.5K到18K 一个程序员的5年成长之路
https://www.csdn.net/article/2013-05-13/2815252
绩效考核:
法制:kpi
1、缺陷密度、遗漏缺陷率、
项目过程符合率(时间进度)
2、线上bug数(和漏测一样)
3、有多少项目延期(这要看和测试是否有关系)
4、为项目出了什么好的建议明显提升了人效
(经验分享)
自动化有啥成绩
性能有啥成绩
安全测试
引入新的工具
你的能力是否有提升
5、成就客户做了哪些
不考核
6、当月所做项目 权重 完成度
开发满意度:
测试满意度:
项目经理打分
7、评定内容:学习能力,团队精神
每个人的指标个性化:主管、经理
8、项目交付率
9、版本交付数
10、360打分
主管主观打分:
1 遵守规章制度
2 是否主动
抱好大腿。
职场生存三原则:
1 听话
2 能干
3 摆正自己位置
总结:知己知彼,做到最好的自己,满足kpi得分,
然后一定要抱好大腿。
播测:脚本失败,发邮件,可能服务挂了
异常
>>> try:
... int("1.1")
... except ValueError:
... print("should input base 10")
... except:
... print("sth wrong")
...
should input base 10
try不能单独存在,必须有except或finally。
>>> try:
... with open("e:\\rrr.txt") as f:
... pass
... except IOError:
... print("io error")
... except:
... print("sth wronf")
...
io error
>>> try:
... 1/0
... except:
... print("value error")
... else:
... print("no error") #else,当没有异常执行else
...
value error
嵌套try
try:
try:
int("1.1")
except:
print("第二层try的异常出现了")
1/0
except:
print ("第一层try的异常出现了")
程序顺序执行,第一个异常被捕获了,所以继续执行1/0。
try:
1/0
try:
int("1.1")
except:
print("第二层try的异常出现了")
except:
print ("第一层try的异常出现了")
1/0 就出现了问题,所以不会继续执行了
#coding=utf-8
try:
fh = open("c:\testfile", "r")
finally:
print ("关闭文件")
fh.close()
因为找不到文件,执行finally这个文件没打开。
#coding=utf-8
try:
fh = open("D:\\test.py", "r")
try:
content = fh.read()
print (content)
finally:
print ("关闭文件")
fh.close()
except IOError:
print ("Error: 没有找到文件或读取文件失败")
#coding=utf-8
try:
fh = open("D:\\test.py", "r",encoding="utf-8")
try:
content = fh.read()
1/0
print (content)
finally:
print ("关闭文件")
fh.close()
except IOError:
print ("Error: 没有找到文件或读取文件失败")
except ZeroDivisionError:
print ("1/0 异常出现了!")
#coding=utf-8
try:
fh = open("e:\\axxx.txt", "r",encoding="utf-8")
except IOError as e:
print (e)
except ZeroDivisionError:
print ("1/0 异常出现了!")
#coding=utf-8
try:
fh = open("e:\\axxx.txt", "r",encoding="utf-8")
except (IOError,ZeroDivisionError) as e:
print (e)
except :
print ("1/0 异常出现了!")
同时捕获多个,用括号放在一起
抛出异常
raise Exception("Invalid num")
自定义异常1
# coding=utf-8
class WXHerror(RuntimeError):
# 重写默认的__init__()方法,
# 抛出特定的异常信息
def __init__(self, value,value1):
self.value = value
self.value1=value1
# 触发自定义的异常
try:
raise WXHerror("Bad hostname","hello Error!")
except WXHerror as e:
print ("WXHerror occurred, value:", e.value1)
自定义异常2
#coding=utf-8
class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = input('Enter something --> ')
if len(s) < 3:
#如果输入的内容长度小于3,触发异常
raise ShortInputException(len(s), 3)
except EOFError:
print ('\nWhy did you do an EOF on me?')
except ShortInputException as x:
print ('ShortInputException: The input was of length %d,\
was expecting at least %d' % (x.length, x.atleast))
else:
print ('No exception was raised.')
自定义with异常
class opened(object):
def __init__(self, filename):
self.handle = open(filename)
print ('Resource: %s'% filename)
def __enter__(self):
print ('[Enter %s]: Allocate resource.' % self.handle)
return self.handle # 可以返回不同的对象
def __exit__(self, exc_type, exc_value, exc_trackback):
print ('[Exit %s]: Free resource.' % self.handle)
if exc_trackback is None:
print ('[Exit %s]: Exited without exception.,' % self.handle)
self.handle.close()
else:
print ("error occur!") #句柄泄漏
#return True
return False #会抛出异常,中断程序的执行
with opened(r'D:\test.py) as fp:
for line in fp.readlines():
print(line)
raise TypeError
print ("Done")
断言 assert
>>> try:
... assert 1==2
... except AssertionError:
... print("assert fail!")
...
assert fail!
模块:
模块是一个python文件,包是一个目录,__init__.py
test1.py
a=1
def add(a,b):
return a+b
class P(object):
value=100
test2.py
import test1
print (test1.a)
print (test1.add(1,2))
print (test1.P.value)
不在一个目录中
import sys
sys.path.append("d:\\") #把这个被引入的路径加上,
import sys
sys.path.extend(["d:\\","c:\\"]) #可添加多个
如果都找不到,python会查安装路径lib下的site-packages。Unix下,默认路
径一般是/usr/local/python/。
引入模块
- 相同目录
- Sys.path
- 放在site-packages下
- 设置一个pythonpath。
from b import * #1这种情况可以省去b.
from b import a,P,add #2这种情况可以省去b.
print (a)
print (add(1,2))
print(P.value)
import XX,xx的文件都会被执行,除了if __name__ == “__main__”: 里面的。
if __name__ == “__main__”: #如果这个文件被导入,不会被执行
print(“xxx”)
当文件被引用的时候 __name__ = 文件名,当自己执行时,__name__ =__main__
包: 模块文件 + __init__.py
from 模块 import 包名
import 模块.包名