如何在Python中从stdout中移除\n和\r\n?

4

我有这个脚本:

#!/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', 'Info: The max number of VTY users is 10, and the number\r\n', ' of current VTY users on line is 2.\r\n', ' The current login time is 2017-07-20 20:10:54+03:00 DST.\r\n', '-------------------------------------------------------------------------------\r\n', 'MAC Address VLAN/VSI Learned-From Type \r\n', '-------------------------------------------------------------------------------\r\n', '0123-4567-8910 1234/- Eth-Trunk9 dynamic \r\n', '\r\n', '-------------------------------------------------------------------------------\r\n', 'Total items displayed = 1 \n', '\r\n', '']
我该如何删除'\ n'和'\ r \ n'或至少用空格替换它们,以使结果看起来像原始结果? 我确实阅读了很多关于这个问题的答案,但没有一个能帮助。

1
欢迎来到 [so]!您能否[编辑]您的问题并包含一个您想要输出结果的示例吗? - TemporalWolf
3个回答

6
你的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

非常感谢。我刚刚测试了一下,它运行得很好,而且我完全理解了问题 :D - isus hristos
尝试点赞,但我的声望还很低,不到15。我已经接受了答案。再次感谢一切。 - isus hristos

2
你可以使用.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', '', '']

-1
您可以使用以下代码来删除 '\n' 和 '\r\n'。
with subprocess.Popen(["ssh", "%s" % HOST, COMMAND], shell=False) as ssh:
        result = ssh.communicate()[0]
        print(result)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接