Skip to main content
 首页 » 编程设计

Python 从 readlines() 读取前四行

2025年05月04日11三少

我如何从 readlines() 中读取前四行,我正在从代理获取一个 STDIN 到我的脚本:

GET http://www.yum.com/ HTTP/1.1 
Host: www.yum.com 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Language: en-gb,en;q=0.5 
Accept-Encoding: gzip, deflate 
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 
Proxy-Connection: keep-alive 

我使用 sys.stdin.readlines() 读取它并将其记录到文件中,但我只想记录 GET 和 User-Agent行到文件。

while True: 
    line = sys.stdin.readlines() 
    for l in line: 
        log = open('/tmp/redirect.log', 'a') 
        log.write(l) 
        log.close() 

请您参考如下方法:

使用with 确保日志的良好关闭。 您可以像 Python 中的任何文件类型对象一样遍历 sys.stdin,这更快,因为它不需要创建列表。

with open('/tmp/redirect.log', 'a') as log: 
    while True: #If you need to continuously check for more. 
        for line in sys.stdin: 
            if line.startswith(("GET", "User-Agent")): 
                log.write(line) 

以下是一种有效的方法,因为它不会一次又一次地检查相同的行,而只会在还剩下需要的行时进行检查。在这种情况下可能不需要,但是如果您有更多的项目要检查,并且有更多的事情要整理,那么就值得做。这也意味着您要跟踪您拥有的部分,并且不要阅读超出您需要的内容。如果阅读是一项昂贵的操作,这可能很有值(value)。

with open('/tmp/redirect.log', 'a') as log: 
    while True: #If you need to continuously check for more. 
        needed = {"GET", "User-Agent"} 
        for line in sys.stdin: 
            for item in needed: 
                if line.startswith(item): 
                    log.write(line) 
                    break 
            needed.remove(item) 
            if not needed: #The set is empty, we have found all the lines we need. 
                break 

该集合是无序的,但我们可以假设行将按顺序排列,因此按顺序记录。

更复杂的行检查可能也需要这种设置(例如:使用正则表达式)。但是,对于您的情况,第一个示例很简洁并且应该运行良好。