【问题标题】:Get return value from shell command in python从python中的shell命令获取返回值
【发布时间】:2015-05-09 04:20:37
【问题描述】:

我正在使用os.system 跟踪实时文件,grep 跟踪字符串 grep 成功后如何执行某些操作? 例如

cmd=  os.system(tail -f file.log | grep -i abc)
if (cmd):     
         #Do something and continue tail

有什么办法可以做到吗?只有在os.system语句完成后才会到if块。

【问题讨论】:

    标签: python shell unix


    【解决方案1】:

    您可以使用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)
    

    【讨论】:

      【解决方案2】:
      1. 我不确定您是否真的需要在 python 中执行此操作 - 也许将 tail-f 输出通过管道传输到 awk 会更容易:https://superuser.com/questions/742238/piping-tail-f-into-awk

      2. 如果你想在python中工作(因为你需要在之后做一些处理)然后查看这个链接如何使用tail -fHow can I tail a log file in Python?

      【讨论】:

        猜你喜欢
        • 2022-08-20
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-04
        相关资源
        最近更新 更多