使用RE让Python在某个时间停止从文件中打印行
基本上,我要做的是让它打印在用户输入的特定范围内具有时间戳的文件行。
import sys, re
f = open('log.txt', encoding='ISO-8859-1')
h = open('errorsfound.txt', "w")
print("What time do you want to begin searching the logs?")
starttimestamp = input()
starttimestamp = str(starttimestamp)
print("What time do you want to stop searching the logs?")
endtimestamp = input()
endtimestamp = str(endtimestamp)
use = False
lines = f.readlines()
for line in lines:
if re.search(starttimestamp, line): use = True
if re.search(endtimestamp, line): use = False
if use:
if "error" in line:
h.write (line)
if use:
if "Failed" in line:
h.write (line)
if use:
if "ERROR" in line:
h.write (line)
if use:
if "WARN" in line:
h.write (line)
if use:
if "Requeue:" in line:
h.write (line)
f.close()
h.close()
从一定时间开始,我可以将其打印到印刷品,但是在一定时间后我很难停止打印。时间戳为格式04:00:48。因此,当它提示时,我输入说04:00:48作为开始时间,而04:15:48作为结束时间。我是一个相当新的编码员,所以如果我遗漏了任何东西,我深表歉意。谢谢您的查看!
Basically what I am trying to do is to get it to print the lines of a file that have a timestamp in a specific range that is input from the user.
import sys, re
f = open('log.txt', encoding='ISO-8859-1')
h = open('errorsfound.txt', "w")
print("What time do you want to begin searching the logs?")
starttimestamp = input()
starttimestamp = str(starttimestamp)
print("What time do you want to stop searching the logs?")
endtimestamp = input()
endtimestamp = str(endtimestamp)
use = False
lines = f.readlines()
for line in lines:
if re.search(starttimestamp, line): use = True
if re.search(endtimestamp, line): use = False
if use:
if "error" in line:
h.write (line)
if use:
if "Failed" in line:
h.write (line)
if use:
if "ERROR" in line:
h.write (line)
if use:
if "WARN" in line:
h.write (line)
if use:
if "Requeue:" in line:
h.write (line)
f.close()
h.close()
I have it to where it prints starting from a certain time, but I'm having trouble getting it to stop printing after a certain time. The timestamps are in format 04:00:48. So when it prompts I input say 04:00:48 as the start time and 04:15:48 as the end time. I am a fairly new coder so I apologize if I have left anything out. Thank you for looking!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为一个新的编码器,您缺少某种格式,但无论如何工作!
在时间的时间里,您应该习惯使用诸如DateTime之类的模块,使用str()输入是多余的(如果在排队中的my_text:然后x),但是无论如何,re是一个不错的工具。
As a new coder you are missing some format but good job anyways!
For time you should get used to use modules like datetime, using str() on input is redundant since it saves the result of the input as str already, and least but not last re is for regular expressions, there are other ways of parsing text ( if my_text in line: then x) but re is a good tool anyways.