【问题标题】:Python subprocess - Run shell command and do something on specific command outputPython 子进程 - 运行 shell 命令并对特定命令输出执行某些操作
【发布时间】:2020-08-06 17:49:04
【问题描述】:

我正在编写一个用于自动化的 python 脚本。

我需要运行一个 linux shell 命令(程序:dvbv5-zap)并等待特定的命令输出(DVR interface '/dev/dvb/adapter0/dvr0' can now be opened)。当命令输出这个字符串时,python 应该运行另一个 shell 程序。

我不知道如何捕获子进程 cli 输出,我尝试使用 .stdout.readline(),但我一无所获。 我用subprocess.Popen(['dvbv5-zap', 'args'], stdout=subprocess.PIPE) 运行命令

【问题讨论】:

    标签: python subprocess stdout


    【解决方案1】:

    我在这里找到了答案:https://fredrikaverpil.github.io/2013/10/11/catching-string-from-stdout-with-python/

    代码sn-p:

    # Imports
    import os, sys, subprocess
    
    # Build command
    command = [ 'python', os.join.path('/path/to', 'scriptFile.py') ]
    
    # Execute command
    p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    
    # Read stdout and print each new line
    sys.stdout.flush()
    for line in iter(p.stdout.readline, b''):
    
        # Print line
        sys.stdout.flush()
        print(">>> " + line.rstrip())
    
    
        # Look for the string 'Render done' in the stdout output
        if 'Render done' in line.rstrip():
    
            # Write something to stdout
            sys.stdout.write('Nice job on completing the render, I am executing myFunction()\n' )
            sys.stdout.flush()
    
            # Execute something
            myFunction()
    

    【讨论】:

      猜你喜欢
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 2021-05-15
      相关资源
      最近更新 更多