Python,将Popen流重定向到Python函数

2024-04-18 17:20:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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

以便详细说明这些文件中包含的信息。 这个函数的目的是用三行代码将存储在这些文件中的日志写进一行。。。该函数对从本地计算机读取的文件运行良好,但我无法确定如何连接到远程服务器并创建这些单行日志,而不将每个文件的内容存储为字符串,然后使用字符串。。。我用来连接到远程计算机的命令是:

connection_out = Popen(['ssh', retList[0], 'cd '+retList[2]+'; cat'+fileName], stdout=PIPE).communicate()[0]

retList[0]和retList[2]是用户@remote和我必须访问的文件夹名

提前感谢大家!

更新:

我的问题是,我必须先建立一个ssh连接:

pr1=Popen(['ssh', 'siatc@lgssp101', '*~/XYZ/AAAAA/log_archive/00/MSG_090308_162648.gz*' ], stdout=PIPE).communicate()[0]

我需要打开的所有文件都存储在一个列表中,fileList[],其中一部分是压缩的(.gz),另一部分只是文本文件!!我已经试过了你在机器人出现之前的所有程序什么都没用。。。我想我应该修改Popen函数的第三个参数,但是我不知道怎么做!有人能帮我吗???


Tags: 文件the函数logifcounterfilenameout
3条回答

如果您想通过ssh做一些事情,为什么不使用the Python SSH module

您不必亲自将流/文件拆分成行。只是重复:

for ln in f:
    # work on line in ln

对于文件(使用open()for file())和管道(使用Popen),这应该同样有效。使用popen对象的stdout属性访问连接到子进程stdout的管道

示例

from subprocess import Popen, PIPE
pp = Popen('dir', shell=True, stdout=PIPE)

for ln in pp.stdout:
    print '#',ln

删除InStream并只使用file对象。

这样你的代码就会读到:

for nextLine in f.readlines():
    .
    .
    .

贝尔说得对。

为了澄清,文件对象的默认迭代行为是返回下一行。因此,f中nextLine的“”将给出与f.readlines()中nextLine的“相同的结果。

有关详细信息,请参阅文件对象文档:http://docs.python.org/library/stdtypes.html#bltin-file-objects

相关问题 更多 >