Python从readlines读取前四行()

kri*_*itx 1 python

我如何阅读前四行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
Run Code Online (Sandbox Code Playgroud)

我使用它sys.stdin.readlines()并将其记录到文件,但我想只记录GETUser-Agent行到文件.

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

Gar*_*tty 5

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

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)
Run Code Online (Sandbox Code Playgroud)

以下是一种有效的方法,因为它不会一次又一次地检查相同的行,并且仅在需要剩余的行时进行检查.考虑到这种情况,可能不需要,但是如果你有更多要检查的物品,还有更多需要整理的东西,那么值得做.它还意味着您可以跟踪您拥有的部件,并且不会超出您需要的范围.如果阅读是一项昂贵的操作,这可能是有价值的.

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
Run Code Online (Sandbox Code Playgroud)

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

对于更复杂的行检查(例如:使用正则表达式),也可能需要这种设置.然而,在你的情况下,第一个例子是简洁的,应该运作良好.