Python子流程运行shell命令并对特定命令输出执行某些操作

2024-09-26 18:05:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为自动化编写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)运行一个命令


Tags: dev命令程序脚本linuxstdoutshellinterface
1条回答
网友
1楼 · 发布于 2024-09-26 18:05:17

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

代码段:

# 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()

相关问题 更多 >

    热门问题