我正在阅读一个包含以下数据列表的远程文件:
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"用空字符串。
谢谢
答案 0 :(得分:1)
splitlines()
的文档很清楚:
换行符不包含在结果列表中,除非给出了keepends并且为true。
所以尝试改变这个:
result = ssh.stdout.read().splitlines()
为:
result = ssh.stdout.read().splitlines(True)
当然,您也可以使用join()
lines = "\r".join(result)
分隔符可以是任何东西,例如回车。
答案 1 :(得分:1)
鉴于您的新问题描述:
fullstring = ssh.stdout.read() ## will contain all the /bytes/ from stdout
split = fullstring.split('\r') ## will make substrings without the trailing `\r`
fullsplits = [s + '\r' for s in split] ## adding the \r back to the strings
答案 2 :(得分:1)
尝试用逗号+回车符替换逗号
result = str(result)
result = result.replace(",",",\n")
答案 3 :(得分:0)
好吧,你具体告诉python摆脱它:
result = ssh.stdout.read().splitlines()
将事物分成几行,消耗掉行符号。 不要那样做,你会没事的。
答案 4 :(得分:0)
splitlines有一个可选参数 - keepends。见https://docs.python.org/2/library/stdtypes.html
你必须调用splitlines(True)