我正在读取一个远程文件,其中包含如下数据列表:
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/