簡體   English   中英

如何擺脫日志文件中的^ M

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

我是python的新手。 我在一個文件telnet.py使用telnet連接,並在另一個文件debug.py 但是在成功的telnet連接之后,當我查看日志文件時,我看到在日志文件的每一行中都添加了^M 有人可以指導我擺脫日志文件中的^M嗎? 提前致謝。

文件名:telnet.py

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

檔名: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)

日志文件日志如下:

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

收到消息時,只需修剪\\r\\n並重新添加\\n

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

如果消息可能是多行,請拆分並重新組裝:

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

使用re可以找到,然后用模式替換匹配的字符串。 re.sub對您而言做得很好。

import re 

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

print(res, string)

您可以讀取日志文件,並在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