python - 读取远程文件时回车丢失

标签 python

我正在读取一个远程文件,其中包含如下数据列表:

HTTP threads 200
HornetQ Server threads 100
HornetQ Client threads 16
Default threads 22
OOB threads 20

我使用以下 python 代码远程读取文件:

import subprocess
import sys

HOST="myhost"

COMMAND="cat /space/monitor/monitor.log"

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

代码的输出显示不带回车的行列表:

'Thu Jul 2 13:25:01 CEST 2015', 'HTTP threads 200', 'HornetQ Server threads 100', 'HornetQ Client threads 14', 'Default threads 22', 'OOB threads 20', 'Remoting threads 12', 'Thu Jul 2 13:30:01 CEST 2015', 'HTTP threads 200', 'HornetQ Server threads 100', 'HornetQ Client threads 17', 'Default threads 22', 'OOB threads 20', 'Remoting threads 12', 'Thu Jul 2 13:35:01 CEST 2015', 'HTTP threads 200', 'HornetQ Server threads 100', 'HornetQ Client threads 13', 'Default threads 22', 'OOB threads 20', 'Remoting threads 12', 'Thu Jul 2 13:40:01 CEST 2015', 'HTTP threads 200', 'HornetQ Server threads 100', 'HornetQ Client threads 11', 'Default threads 22', 'OOB threads 20', 'Remoting threads 12', 

更新: 在我的第一次尝试中,我使用了:

result = ssh.stdout.readlines()

但是这会产生“\n”来替换回车符:

 20\n', 'Remoting threads 12\n', 'Thu Jul 2 13:55:01 CEST 2015\n', 'HTTP threads 200\n', 'HornetQ Server threads 100\n', 'HornetQ Client threads 12\n', 'Default threads 22\n', 'OOB threads 20\n', 'Remoting threads 12\n', 'Thu Jul 2 14:00:01 CEST 2015\n', 'HTTP threads 200\n', 'HornetQ Server threads 100\n', 'HornetQ Client threads 12\n', 'Default threads 22\n', 'OOB threads 20\n', 'Remoting threads 12\n', 'Thu Jul 2 14:05:01 CEST 2015\n', 'HTTP threads 200\n', 'HornetQ Server threads 100\n', 'HornetQ Client threads 15\n', 'Default threads 22\n', 'OOB threads 20\n', 'Remoting threads 12\n']

我认为分割线可以解决这个问题 - 但它只是用空字符串替换了“\n”。

谢谢

最佳答案

尝试用逗号+回车符替换逗号

result = str(result)
result = result.replace(",",",\n")

关于python - 读取远程文件时回车丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31184033/

相关文章:

Python 自定义 getopt

Python/Django : log to console under runserver, 在 Apache 下登录到文件

python - matplotlib 不均匀组大小条形图并排

python - 用另一个列表索引一个二维列表

python - 新手 Django : Creating a project with several apps or all in one

python - 如何将自定义指标的值从自定义回调附加到我需要在张量板中使用的 "logs"?

python - 将定位器存储在变量中

python - 如何使用drive-sdk共享文件?

python - Python 中的表单生成/验证库

python - 使用 Scapy 解析 PPPoE 标签