从python中的shell命令获取返回值 [英] Get return value from shell command in python
本文介绍了从python中的shell命令获取返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用 os.system
跟踪实时文件,用 grep
跟踪字符串grep 成功时如何执行某些操作?例如
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
cmd= os.system(tail -f file.log | grep -i abc)
if (cmd):
#Do something and continue tail
有什么办法可以做到这一点?只有当os.system语句完成时才会来到if
块.
Is there any way I can do this? It will only come to the if
block when the os.system statement is completed.
推荐答案
您可以使用 subprocess.Popen
并从 stdout 中读取行:
You can use subprocess.Popen
and read lines from 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 line in tail('test.log'):
if line.startswith('error'):
print('Error:', line)
这篇关于从python中的shell命令获取返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文