使用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)以下是一种有效的方法,因为它不会一次又一次地检查相同的行,并且仅在需要剩余的行时进行检查。考虑到这种情况,可能不需要,但是如果你有更多要检查的物品,还有更多东西可以分类,那么值得做。它还意味着您可以跟踪您拥有的部件,并且不会超出您需要的范围。如果阅读是一项昂贵的操作,这可能是有价值的。
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该集合是无序的,但我们可以假设这些行将按顺序排列,因此按顺序记录。
对于更复杂的行检查(例如:使用正则表达式),也可能需要这种设置。然而,在你的情况下,第一个例子是简洁的,应该运作良好。