HxUtils: 批量转换换行符,print2to3
在 windows 和 linux 系统,换行符有时需要转换,其代码文件 HxUntils.py 如下:
''' HxUtils.py 2018 by x01 ''' import os, sys def convert_endlines(filepath, tounix=True): try: oldfile = open(filepath, 'rb+') path, name = os.path.split(filepath) newfile = open(path + '$' + name, 'ba+') old = b'\r' new = b'' if not tounix: old = b'\n' new = b'\r\n' while True: olddata = oldfile.read(1024) newdata = olddata.replace(old, new) newfile.write(newdata) if len(olddata) < 1024: break newfile.close() oldfile.close() os.remove(filepath) os.rename(path + '$' + name, filepath) except IOError as e: print(e) def convert_endlines_for_dir(): dirpath, tounix, extname = ('.', True, '.py') if len(sys.argv) == 2: dirpath = sys.argv[1] elif len(sys.argv) == 3: dirpath, tounix = (sys.argv[1], sys.argv[2]) elif len(sys.argv) == 4: dirpath, tounix, extname = (sys.argv[1], sys.argv[2], sys.argv[3]) for (thisdir, subshere, fileshere) in os.walk(dirpath): for filename in fileshere: if filename.endswith(extname): #print(os.path.join(thisdir,filename)) convert_endlines(os.path.join(thisdir,filename), tounix) if __name__ == '__main__': convert_endlines_for_dir()
使用方法如下:
$ python3 HxUntils.py [dirpath tounix extname]
python2 的 print 命令替换为 python3 的 print() 函数:
def convert_print(dirpath='.'): ''' 转换 python2 中的 print 命令到 python3 ''' if len(sys.argv) == 2: dirpath = sys.argv[1] for (thisdir, subshere, fileshere) in os.walk(dirpath): for filename in fileshere: if filename.endswith('.py'): print2to3(os.path.join(thisdir,filename)) def print2to3(filename): fr = open(filename) tempfile = open(filename +'.tmp', 'a+') for line in fr: tl = replace_line(line) tempfile.write(tl) fr.close() tempfile.close() os.remove(filename) os.rename(filename+'.tmp', filename) def replace_line(line): if 'print(' in line: return line tl = '' pattern = r'(".*?;.*?")|(\'.*?;.*?\')' result = re.search(pattern, line) if result and ('print ' in line): line = line.replace('print ', 'print(') line = line[:len(line)-1] + ')' + line[len(line)-1:] return line if ('print' in line) and (';' not in line): index = line.index('print') tl += line[:index+5] + '(' + line[index+6:len(line)-1] + ')' + line[len(line)-1:] # endline \n elif ('print' in line) and (';' in line): i1 = line.index('print') i2 = line.index(';') tl += line[:i1+5] + '(' + line[i1+6:i2] + ')' + line[i2:] if 'print' in line[i2:]: tl += replace_line(line[i2:]) else: tl = line return tl
借用 lib2to3 如下,添加 convert_2to3() 到 HxUtils.py 中:
def convert_2to3(): ''' usage: python3 HxUtils.py -w [dirpath] ''' import sys from lib2to3.main import main sys.exit(main("lib2to3.fixes"))