Python无法识别nano/vi显示的^M(\r)回车符,求日志处理方案
解决日志中的\r检测问题及精简日志方法
一、解决Python无法检测\r的问题
Python默认以文本模式读取文件时,会自动将\r\n转换为\n,导致\r被隐式处理,所以检测不到。可以通过以下两种方式解决:
1. 二进制模式读取文件
直接读取原始字节内容,保留所有控制字符:
with open('your_logfile.log', 'rb') as f: content_bytes = f.read() # 统计\r的数量 cr_count = content_bytes.count(b'\r') print(f"\r的数量:{cr_count}") # 搜索\r的位置 import re match = re.search(b'\r', content_bytes) if match: print(f"找到\r,位置:{match.start()}")
2. 文本模式指定newline=''
此模式会保留原始换行符序列,不做自动转换:
with open('your_logfile.log', 'r', newline='', encoding='utf-8') as f: content = f.read() # 统计\r的数量 cr_count = content.count('\r') print(f"\r的数量:{cr_count}") # 搜索\r的位置 import re match = re.search(r'\r', content) if match: print(f"找到\r,位置:{match.start()}")
二、精简日志,仅保留最后一条成功进度信息
这类日志是通过\r覆盖行内容实现的动态进度,最后一条进度就是所有\r之后的最终内容,可用以下方法提取:
1. Bash命令处理
直接提取最后一个\r之后的内容:
# 方法1:用awk去掉所有\r之前的内容 awk '{sub(/.*\r/,""); print}' your_logfile.log # 方法2:用grep匹配最后一段非\r内容 grep -o '[^\r]*$' your_logfile.log # 方法3:用tr删除所有\r后取最后一行(如果日志末尾有换行) tr -d '\r' < your_logfile.log | tail -1
2. Python脚本处理
读取日志后分割取最后一段:
with open('your_logfile.log', 'r', newline='', encoding='utf-8') as f: content = f.read() # 按\r分割后取最后一段,去除首尾空白 last_progress = content.split('\r')[-1].strip() print("最后一条进度:", last_progress)
内容的提问来源于stack exchange,提问作者iolim5678
相关产品推荐
相关产品推荐

