Python子进程控制outpu

2024-10-06 12:39:18 发布

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

我有一个基本python项目,它可以接受其他python文件并将它们作为子进程执行。基本项目接受用户输入,将其反馈给子进程,然后子进程执行代码并通过stdout返回一个值,该值被反馈给用户。你知道吗

在base程序中,我做了一些类似于:

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

然后在子流程中,我有如下内容:

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

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

是否有一种方法可以在我的最终输出语句之前清除stdout缓冲区,这样子进程返回的值中就不会包含任何散乱的打印或输出?你知道吗

编辑:我试过系统标准缓冲区.flush(),系统标准冲洗()就在最后一个调用之前,希望它能清除缓冲区,但之前的print语句似乎仍然与最终返回值一起发送。你知道吗


Tags: 文件数据项目用户标准进程系统stdout
3条回答

试试这个:

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

也许这对你有帮助。你知道吗

可以使用子进程Popen、PIPE任务.if您希望使用多个子流程实例这里是链接

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开始了

这可能不是您要寻找的答案,但这可能是一种解决方法:

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

相关问题 更多 >