whe*_*erg 6 python subprocess yield stream popen
我是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
Run Code Online (Sandbox Code Playgroud)
为了详细说明这些文件中包含的信息.该函数的目的是只用1行写入使用3行存储在这些文件中的日志...该函数在从我的本地机器读取的文件上工作正常,但我无法弄清楚如何连接到远程服务器和创建这些单行日志而不将每个文件的内容存储到字符串中然后使用字符串...我用来连接到远程计算机的命令是:
connection_out = Popen(['ssh', retList[0], 'cd '+retList[2]+'; cat'+fileName], stdout=PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
retList [0]和retList [2]是用户@ remote和我必须访问的文件夹名称
感谢所有提前!
更新:
我的问题是我必须先建立一个ssh连接:
pr1=Popen(['ssh', 'siatc@lgssp101', '*~/XYZ/AAAAA/log_archive/00/MSG_090308_162648.gz*' ], stdout=PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
我需要打开的所有文件都存储在列表中,fileList [],其中一部分是压缩的(.gz),部分只是文本文件!! 我已经尝试过你在机器人没有工作之前显示的所有程序......我认为我修改了Popen函数的第三个参数但我无法弄清楚如何做到这一点!有没有人可以帮助我???
您不必自己将流/文件拆分为行.只是迭代:
for ln in f:
# work on line in ln
Run Code Online (Sandbox Code Playgroud)
这应该对文件(使用open()for file())和管道(使用Popen)同样有效.使用stdoutpopen对象的属性访问连接到子进程的stdout的管道
例
from subprocess import Popen, PIPE
pp = Popen('dir', shell=True, stdout=PIPE)
for ln in pp.stdout:
print '#',ln
Run Code Online (Sandbox Code Playgroud)