在python中从shell命令获取返回值
我正在用在python中从shell命令获取返回值,python,shell,unix,Python,Shell,Unix,我正在用os.system跟踪一个实时文件,用grep跟踪一个字符串 当grep成功时,我如何执行某些操作? 比如说 cmd= os.system(tail -f file.log | grep -i abc) if (cmd): #Do something and continue tail 我有什么办法可以做到这一点吗?当os.system语句完成时,它只会出现在if块。您可以使用subprocess.Popen并从标准输出读取行: import subpro
os.system
跟踪一个实时文件,用grep
跟踪一个字符串
当grep成功时,我如何执行某些操作?
比如说
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会更容易:tail-f
: