Python中,重定向POPEN的流Python函数
-
19-08-2019 - |
题
我是新来的Python编程。 我有这样的问题:我有一个文本文件(压缩和未)的列表,我需要: - 连接到服务器,并打开它们 - 文件开通后,我需要他的内容并把它传递给我写了另一个Python功能
def readLogs (fileName):
f = open (fileName, 'r')
inStream = f.read()
counter = 0
inStream = re.split('\n', inStream) # Create a 'list of lines'
out = "" # Will contain the output
logInConst = "" # log In Construction
curLine = "" # Line that I am working on
for nextLine in inStream:
logInConst += curLine
curLine = nextLine
# check if it is a start of a new log && check if the previous log is 'ready'
if newLogRegExp.match(curLine) and logInConst != "":
counter = counter + 1
out = logInConst
logInConst = ""
yield out
yield logInConst + curLine
def checkFile (regExp, fileName):
generatore = readLogs(fileName)
listOfMatches=[]
for i in generatore: #I'm now cycling through the logs
# regExp must be a COMPILE regular expression
if regExp.search(i):
listOfMatches.append(i)
return listOfMatches
为了阐述包含在这些文件中的信息。 该函数写在短短的1号线存储在使用3行这些文件中的日志...功能工作正常,从我的本地机器读取文件的目的,但我无法弄清楚如何连接到远程服务器,并而不每个文件的内容存储到一个字符串,然后用字符串工作创建这些一行日志...,我使用连接到远程计算机的命令是:
connection_out = Popen(['ssh', retList[0], 'cd '+retList[2]+'; cat'+fileName], stdout=PIPE).communicate()[0]
retList [0]和retList [2]是用户@远程和文件夹的名称,我必须访问
感谢所有提前!
<强>更新强>
我的问题是,我必须先建立SSH连接:
pr1=Popen(['ssh', 'siatc@lgssp101', '*~/XYZ/AAAAA/log_archive/00/MSG_090308_162648.gz*' ], stdout=PIPE).communicate()[0]
所有我需要打开存储在列表中的文件,的fileList [],其中一部分被压缩(。广州)及部分只是文本文件!我已经尝试了所有之前的机器人毫无效果......我想,我每亩修改POPEN函数的第三个参数ü显示的程序,但我无法弄清楚如何做到这一点!是否有任何人能帮助我吗?
解决方案
您不必流/文件分割成线自己。只是迭代:
for ln in f:
# work on line in ln
此应该工作同样适用于文件(使用open()用于文件())和导管(使用POPEN)。使用POPEN对象的属性stdout
访问连接到子进程的标准输出的管
示例强>
from subprocess import Popen, PIPE
pp = Popen('dir', shell=True, stdout=PIPE)
for ln in pp.stdout:
print '#',ln
其他提示
移除插播,只是使用的文件对象。
所以,你的代码将改为:
for nextLine in f.readlines():
.
.
.
误码率有它的权利。
要澄清,文件对象的默认迭代行为是返回下一行。因此 “作为nextLine f中强>” 会给你相同的结果 “的为nextLine在f.readlines()强>”。
详细情况请参考文件对象文档: HTTP://文档.python.org /库/ stdtypes.html#bltin文件对象
如果您希望通过SSH做的事情,为什么不使用 Python的SSH模块?
试试这个页面上POPEN我迄今发现的最好的信息...