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

时间:2019-03-22 06:26:04

标签: python python-3.x python-2.7

我是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

3 个答案:

答案 0 :(得分:2)

收到消息后,只需修剪任何\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)

答案 1 :(得分:1)

您可以使用my-app/ README.md node_modules/ package.json public/ index.html favicon.ico src/ |components/ |Clien/ |Home.js |Home.css |Header.js |Footer.js |Login.js |admin/ |Dashboard.js |Dashboard.css App.css App.js index.css index.js logo.svg 查找并用模式替换匹配的字符串。 SELECT A.Id_partner ,A.Id_account ,A.Date,A.actual_review ,B.review_recommended FROM table1 AS A LEFT JOIN Review AS B ON A.Id_account = B.Id_account AND A.Id_partner = B.Id_partner 为您做得很好。

re

答案 2 :(得分:1)

您可以读取日志文件,并在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)