python - 如何从 python 的标准输出中删除\n 和\r\n?

标签 python python-2.7

我有这个脚本:

#!/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', '当前登录时间为2017-07-20 20:10:54+03:00 DST.\r\n', '------------ ---------------------------------------------- --------------\r\n', 'MAC 地址 VLAN/VSI 学习类型\r\n', '------------ ---------------------------------------------- ------------------\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

关于python - 如何从 python 的标准输出中删除\n 和\r\n?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45222110/

相关文章:

python - 计算word2vec模型的困惑度

python - 如何将字符串添加到文件中的奇数行?

python - 根据字典键创建具有值的新列

python - 我如何向 Python 中的列表添加限制或规则?

python - 识别最近的网格点

python - 如何在 Odoo/OpenERP 笔记本中动态添加页面?

python - 不使用第三方库在 Python 中逆向已知算法

python - TypeError at/news/, html() 不带参数

python - 如何存储经过训练的分类器?

python - 使用 Google App Engine 实现 "Starts with"和 "Ends with"查询