python 2.6 linecache.getline()和stdin。它是如何工作的?

时间:2018-11-22 22:06:16

标签: python file-io python-2.6

我有一个脚本,该脚本遍历输入行以查找ID字符串的出现,同时跟踪行号。 然后,它向后运行输入以跟踪parentID / childID关系。该脚本接受使用-f标志作为参数的日志文件或管道中stdin的内容。 作为输入部分的日志文件可以正常工作,但是从stdin读取似乎无效。

为了合理清晰起见,我已经包括了脚本中与该部分有关的部分,但是并不希望能够运行它。只是为了向您展示发生了什么事情(围绕FIX协议从事金融服务的任何人都可以识别几件事):

import os
import sys
import linecache

from types import *
from ____ import FixMessage   # custom message class that is used throughout

# Feel free to ignore all the getArgs and validation crap
def getArgs():
    import argparse
    parser = argparse.ArgumentParser(
               description='Get amendment history.')
    parser.add_argument('-f', '--file',
               help="input logfile.'")
    args = parser.parse_args()

    return validateArgs(args)


def validateArgs(args):
    try:
        if sys.stdin.isatty():
            if args.file:
                assert os.path.isfile(args.file.strip('\n')), \
                    'File "{0}" does not exist'.format(args.file)
                args.file = open(args.file, 'r')
        else:
            args.file = sys.stdin
        assert args.file, \
            "Please either include a file with '-f' or pipe some text in"
    except AssertionError as err:
        print err
        exit(1)

    return args    


defGetMessageTrail(logfile, orderId):
    # some input validation
    if isinstance(logfile, StringType):
        try: logfile = open(logfile, 'r')
        except IOError as err: exit(1)
    elif not isinstance(logfile, FileType):
        raise TypeError(
              'Expected FileType and got {0}'.format(type(logfile)))

    linenum  = 0

    # This retrieves the message containing the orderID as well as the linenum
    for line in logfile:
        linenum += 1
        if orderId in line:
            # FixMessage is a custom class that is treated here like
            # a dictionary with some metadata
            # Missing dict keys return 'None'
            # .isvalid is bool results of some text validation
            # .direction is either incoming or outgoing
            # thats all you really need to know
            msg = FixMessage(line)
            if msg.isvalid and msg.direction == 'Incoming':
                yield msg
                break

    # If there is a message parentID, it would be in msg['41']
    if msg['41']:
        messages = findParentMessages(logfile, startline=linenum, msg['41'])
        for msg in messages: yield msg



def findParentMessages(logfile, startline, targetId):
    # Some more input validation
    assert isinstance(logfile, FileType)
    assert isinstance(startline, IntType)
    assert isinstance(targetId, StringType)

    # should just make a integer decrementing generator,
    # but this is fine for the example
    for linenum in range(startline)[::-1]:
        # *** This is where the question lies... ***
        # print(logfile.name) # returns "<stdin>"
        line = linecache.getline(logfile.name, linenum)
        if 'Incoming' in line and '11=' + targetId in line:
            msg = FixMessage(line)
            yield msg
            if msg['41']: findParentMessages(logfile, linenum, msg['41'])
            else: break


def main():
    log = getArgs().file
    trail = getMessageTrail(log, 'ORDER123')


if __name__ == '__main__': main()

问题是,当将stdin作为文件读取时,linecache.getline如何工作?与给定常规文件名后的工作方式有什么不同?

1 个答案:

答案 0 :(得分:0)

linecache.getline()接受文件名,而不是文件对象。当将文件名传递给open()和os.stat()之类的调用时,它的工作方式并非如此。

以供参考:https://github.com/python/cpython/blob/2.6/Lib/linecache.py