I'm doing os.system
to tail for a live file and grep
for a string How can I execute something when the grep succeeds? For example
我正在为os.system做一个实时文件和grep for a string如何在grep成功时执行某些操作?例如
cmd= os.system(tail -f file.log | grep -i abc)
if (cmd):
#Do something and continue tail
Is there any way I can do this? It will only come to the if
block when the os.system statement is completed.
有什么方法可以做到这一点吗?它只会在os.system语句完成时进入if块。
2 个解决方案
#1
You can use subprocess.Popen
and read lines from stdout:
您可以使用subprocess.Popen并从stdout读取行:
import subprocess
def tail(filename):
process = subprocess.Popen(['tail', '-F', filename], stdout=subprocess.PIPE)
while True:
line = process.stdout.readline()
if not line:
process.terminate()
return
yield line
For example:
for line in tail('test.log'):
if line.startswith('error'):
print('Error:', line)
#2
-
I am not sure that you really need to do this in python - perhaps it would e easier to pipe the
tail-f
output into awk: https://superuser.com/questions/742238/piping-tail-f-into-awk我不确定你真的需要在python中这样做 - 也许将tail -f输出管道输入awk会更容易:https://superuser.com/questions/742238/piping-tail-f-into-awk
-
If you want to work in python (because you need to do some processing afterwards) then check this link on how to use
tail -f
: How can I tail a log file in Python?如果你想在python中工作(因为你之后需要进行一些处理),那么检查一下如何使用tail -f的链接:我如何在Python中使用日志文件?
#1
You can use subprocess.Popen
and read lines from stdout:
您可以使用subprocess.Popen并从stdout读取行:
import subprocess
def tail(filename):
process = subprocess.Popen(['tail', '-F', filename], stdout=subprocess.PIPE)
while True:
line = process.stdout.readline()
if not line:
process.terminate()
return
yield line
For example:
for line in tail('test.log'):
if line.startswith('error'):
print('Error:', line)
#2
-
I am not sure that you really need to do this in python - perhaps it would e easier to pipe the
tail-f
output into awk: https://superuser.com/questions/742238/piping-tail-f-into-awk我不确定你真的需要在python中这样做 - 也许将tail -f输出管道输入awk会更容易:https://superuser.com/questions/742238/piping-tail-f-into-awk
-
If you want to work in python (because you need to do some processing afterwards) then check this link on how to use
tail -f
: How can I tail a log file in Python?如果你想在python中工作(因为你之后需要进行一些处理),那么检查一下如何使用tail -f的链接:我如何在Python中使用日志文件?