我在做os.system
来为活动文件添加尾部并为grep
添加一个字符串 如何在grep成功时执行某些操作? 例如在python中从shell命令获取返回值
cmd= os.system(tail -f file.log | grep -i abc)
if (cmd):
#Do something and continue tail
有没有什么办法可以做到这一点?当os.system语句完成时,它只会到达if
块。
我在做os.system
来为活动文件添加尾部并为grep
添加一个字符串 如何在grep成功时执行某些操作? 例如在python中从shell命令获取返回值
cmd= os.system(tail -f file.log | grep -i abc)
if (cmd):
#Do something and continue tail
有没有什么办法可以做到这一点?当os.system语句完成时,它只会到达if
块。
您可以使用subprocess.Popen
和读取标准输出线:
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 line in tail('test.log'):
if line.startswith('error'):
print('Error:', line)
我不知道,你真的需要做到这一点的蟒蛇 - 也许它会更容易地将tail-f
输出输出到awk中:https://superuser.com/questions/742238/piping-tail-f-into-awk
如果你想在Python工作(因为你需要事后做一些处理),然后检查如何使用tail -f
此链接:How can I tail a log file in Python?