首页 > 代码库 > Python_检查程序规范
Python_检查程序规范
1 ‘‘‘ 2 检查Python程序的一些基本规范,例如,运算符两测是否有空格,是否每次只导入一个模块,在不同的功能模块之间是否有空行,注释是否够多,等等 3 ‘‘‘ 4 import sys 5 import re 6 7 def checkFormats(lines,desFileName): 8 fp=open(desFileName,‘w‘) 9 for i, line in enumerate(lines): 10 print(‘=‘*30) 11 print(‘Line:‘,i+1) 12 if line.strip().startwith(‘#‘): 13 print(‘ ‘*10+‘Comments.Pass.‘) 14 fp.write(line) 15 continue 16 flag=True 17 #check operator symbols 18 symbols=[‘,‘,‘+‘,‘-‘,‘*‘,‘/‘,‘//‘,‘**‘,‘>>‘,‘<<‘,‘+=‘,‘-=‘,‘*=‘,‘/=‘] 19 temp_line=line 20 for symbol in symbols: 21 pattern=re.compile(r‘\s*‘+re.escape(symbol)+r‘\s*‘) 22 temp_lie=pattern.split(temp_line) 23 sep=‘ ‘+symbol+‘ ‘ 24 temp_line=sep.join(temp_line) 25 if line !=temp_line: 26 flag=False 27 print(‘ ‘*10+‘You may miss some blank spaces in this line.‘ ) 28 #check import statement 29 if line.strip().startwith(‘import‘): 30 if ‘,‘ in line: 31 flag = False 32 print(‘ ‘*10+"You‘d bbetter import one module at a time.") 33 temp_line=line.strip() 34 modules=modules.strip() 35 pattern=re.compile(r‘\s*,\s*‘) 36 modules=pattern.split(modules) 37 temp_line=‘‘ 38 for module in modules: 39 temp_line +=line[:line.index(‘import‘)] + ‘import ‘+module+‘\n‘ 40 line=temp_line 41 pri_line=lines[i-1].strip() 42 if pri_line and(not pri_line.startwith(‘import‘))and (not pri_line.startwith(‘#‘)): 43 falg=False 44 print(‘ ‘*10+‘You should add a blank line before this line.‘) 45 line=‘\n‘+line 46 after_line=lines[i+1].strip() 47 if after_line and(not after_line.startwith(‘import‘)): 48 flag=False 49 print(‘ ‘*10+‘You should add a blank line after this line.‘) 50 line=line+‘\n‘ 51 #check if there is a blank line before new funtional code block 52 #including the class/function definition 53 if line.strip() and not line.startswith(‘ ‘)and i>0: 54 pri_line=lines[i-1] 55 if pri_line.strip() and pri_line.startwith(‘ ‘): 56 flag=False 57 print(‘ ‘*10 +"You‘d better add a blank line before this line.") 58 line=‘\n‘+line 59 if flag: 60 print(‘ ‘*10+‘Pass.‘) 61 fp.write(line) 62 fp.close() 63 64 if __name__ == ‘__main__‘: 65 fileName=sys.argv[1] #命令行参数 66 fileLines=[] 67 with open(fileName,‘r‘) as fp: 68 fileLines=fp.readline() 69 desFileName=fileName[:-3]+‘_new.py‘ 70 checkFormats(fileLines,desFileName) 71 #check the ratio of comment lines to all lines 72 comments=[line for line in fileLines if line.strip().startswith(‘#‘)] 73 ratio=len(comments)/len(fileLines) 74 if ratio <= 0.3: 75 print(‘=‘*30) 76 print(‘Comments in the file is less than 30%‘) 77 print(‘Perhaps you should add some comments at appropriate position.‘)
Python_检查程序规范
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。