Python 子进程控制输出

Python Subprocess controlling output

我有一个基础 python 项目,它可以接受其他 python 文件并将它们作为子进程执行。基础项目接受用户输入,将其提供给子流程,然后子流程执行代码并通过标准输出 returns 一个值,该值被反馈给用户。

在基本程序中,我正在做类似的事情:

dataReturnValue = subprocess.check_output(['python', pythonScriptPath, json.dumps(inputParams)])

然后在子流程中我有这样的东西:

inputParams = sys.argv[1]
...
...
sys.stdout.write(returnValue)

数据已正确 returned,但我想做的是将数据 returned 限制在 returnValue。现在它 return 是整个子流程中的所有打印语句加上 return 值。这对我来说很有意义,因为它是一种输出形式,打印类似于标准输出包装器,但我想更好地控制它。

有没有办法在我的最终输出语句之前清除 stdout 缓冲区,以便子进程 returned 的值中不包含杂散打印或输出?

编辑:我尝试在最后一次调用之前执行 sys.stdout.buffer.flush()、sys.stdout.flush(),希望它能清除缓冲区,但之前的打印语句仍然出现与最终 return 值一起发送。

这可能不是您正在寻找的答案,但也许这是一个可行的解决方法:

dataReturnValue = dataReturnValue.split("\n")[-1]

试试这个:

import sys
import os

# Your code here

with open(os.devnull, 'w') as sys.stdout:
    # Code that you don't want to be printed here
sys.stdout = sys.__stdout__

# Your code here

编辑:

我还给你做了装饰器

import sys
import os

def silence(func, *args, **kwargs):
    def wrapper(*args, **kwargs):
        with open(os.devnull, 'w') as sys.stdout:
            result = func(*args, **kwargs)
        sys.__dict__['stdout'] = sys.__stdout__
        return result
     return wrapper

像这样在任何函数上使用它:

def test1():
    print("TEST1")

@silence
def test2():
    print("TEST2")

def test3():
    print("TEST3")

test1()
test2()
test3()

输出:

TEST1
TEST3

也许这对你有帮助。

您可以使用 subprocess Popen,PIPE 来完成您的 task.if 您希望在这里使用多个子流程实例 link

Python subprocess: how to use pipes thrice?

如何控制输出?

以下命令(虚拟命令)将生成 100 行,但我只需要一行包含文本 'Appium Started'

from subprocess import Popen,PIPE
command='appium-p 4723'
p1=Popen(command,stdout=Pipe)

return_value= 'Started Appium'

#this will store the output which command generated 
output = p3.communicate()[0]

for line in output:
    if returnvalue in line:
        print line
    else:
        pass

最后你只会得到你想要的行,即 Appium Started