我正在做os.system
追踪实时文件并grep
对于一个字符串
grep 成功后如何执行某些操作?
例如
cmd= os.system(tail -f file.log | grep -i abc)
if (cmd):
#Do something and continue tail
我有什么办法可以做到这一点吗?它只会来到if
当 os.system 语句完成时阻塞。
您可以使用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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)