繁体   English   中英

如何从python中的stdout中删除\\ n和\\ r \\ n?

[英]How can I remove \n and \r\n from stdout in python?

我有这个脚本:

#!/usr/bin/python

import subprocess
import sys

HOST="cacamaca.caca"
COMMAND="display mac-address 0123-4567-8910"

ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
                       shell=False,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
    error = ssh.stderr.readlines()
    print >>sys.stderr, "ERROR: %s" % error
else:
    print result

因为输出包含空格和不同的行,所以它也输出回车符和新行,因此结果不是干净的:

['\\ r \\ n','cacamaca.caca \\ r \\ n','信息:在线的VTY用户的最大数量为10,而当前在线的VTY用户的数量为'r \\ n','为2。\\ r \\ n','当前登录时间为DST 2017-07-20 20:10:54 + 03:00。\\ r \\ n','---------------- -------------------------------------------------- ------------- \\ r \\ n','从类型\\ r \\ n学习到的MAC地址VLAN / VSI,'-------------- -------------------------------------------------- --------------- \\ r \\ n','0123-4567-8910 1234 /-Eth-Trunk9动态\\ r \\ n','\\ r \\ n','- -------------------------------------------------- --------------------------- \\ r \\ n','显示的总项目数= 1 \\ n','\\ r \\ n', ”]

如何删除'\\ n'和'\\ r \\ n'或至少用空格替换它们,以使结果看起来像原始的? 我确实阅读了很多有关此问题的答案,但没有一个帮助。

您的result变量是一个列表。 我认为您想将结果加入单个字符串并打印出来。 你可以这样用str.join()做到这一点

print ''.join(result)

这将导致以下输出

cacamaca.caca
Info: The max number of VTY users is 10, and the number
 of current VTY users on line is 2.
 The current login time is 2017-07-20 20:10:54+03:00 DST.
-------------------------------------------------------------------------------
MAC Address VLAN/VSI Learned-From Type
-------------------------------------------------------------------------------
0123-4567-8910 1234/- Eth-Trunk9 dynamic

-------------------------------------------------------------------------------
Total items displayed = 1

您可以使用.strip()删除换行符,或使用.replace()替换它们,例如:

result = [x.strip() for x in result]

输出:

['', 'cacamaca.caca', 'Info: The max number of VTY users is 10, and the number', 'of current VTY users on line is 2.', 'The current login time is 2017-07-20 20:10:54+03:00 DST.', '-------------------------------------------------------------------------------', 'MAC Address VLAN/VSI Learned-From Type', '-------------------------------------------------------------------------------', '0123-4567-8910 1234/- Eth-Trunk9 dynamic', '', '-------------------------------------------------------------------------------', 'Total items displayed = 1', '', '']

您可以使用以下代码删除“ \\ n”和“ \\ r \\ n”。

with subprocess.Popen(["ssh", "%s" % HOST, COMMAND], shell=False) as ssh:
        result = ssh.communicate()[0]
        print(result)

暂无
暂无

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

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