简体   繁体   English

如何摆脱日志文件中的^ M

[英]How to get rid of ^M in log file

I am new to python. 我是python的新手。 I am using a telnet connection in one file telnet.py and logging in another file debug.py . 我在一个文件telnet.py使用telnet连接,并在另一个文件debug.py But after a successful telnet connection when I looked at the log file, I see ^M added in every line of log file. 但是在成功的telnet连接之后,当我查看日志文件时,我看到在日志文件的每一行中都添加了^M Can someone guide me through this to get rid of ^M in log file? 有人可以指导我摆脱日志文件中的^M吗? Thanks in advance. 提前致谢。

filename: telnet.py 文件名:telnet.py

tn = telnetlib.Telnet(HOST)
cmdout = tn.read_until(b"ogin")
Logging(str(cmdout))
tn.write(user.encode('ascii') + b"\r")

filename: debug.py 档名:debug.py

LOG_FILE = 'testing.log'
logging.basicConfig(filename=LOG_FILE, level=logging.DEBUG, format='% 
                    (asctime)s: %(levelname)s: %(message)s')

log = logging.getLogger()
def Logging(msg):
    log.debug(msg)

Logfile logs are below: 日志文件日志如下:

switch login
2019-03-22 11:33:37,623: DEBUG: : Password:
2019-03-22 11:33:37,927: DEBUG:  ^M
^M
Establishing connection...   Please wait.^M
^M
   *****************************************************^M
   *                                                   *^M
   *       Command Line Interface SHell  (CLISH)       *^M

When receiving a message, simply trim any \\r\\n and add the \\n back on. 收到消息时,只需修剪\\r\\n并重新添加\\n

def Logging(msg):
    msg = msg.rstrip('\r\n') + '\n'
    log.debug(msg)

If the message could be multiple lines, split and reassemble: 如果消息可能是多行,请拆分并重新组装:

def Logging(msg):
    lines = [line.rstrip('\r') for line in msg.split('\n')]
    msg = '\n'.join(lines)
    log.debug(msg)

Using re you can find, and then replace the strings that match with a pattern. 使用re可以找到,然后用模式替换匹配的字符串。 re.sub does this perfectly well for you. re.sub对您而言做得很好。

import re 

string = "This is a ^M sample ^M string ^M."
pattern = r'\^M'
res = re.sub(pattern, "", string)

print(res, string)

You can read your log file, and use the replace method in python: 您可以读取日志文件,并在python中使用replace方法:

def remove_caret_m_from_the_old_log_file_and_create_a_new_log_file_without_it():
    # Read the old log file.
    the_file = open("your_log_file.txt", "r")
    initial_content = the_file.read()

    # Remove '^M'.
    desired_content = initial_content.replace('^M', '')

    # Write the new content into a new log file.
    the_new_file = open('your_new_log_file.txt', 'x')
    the_new_file.write(desired_content)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM