Skip to content

How to intercept the stdout and output the information to web page #21

Answered by wang0618
lifeofpi2012 asked this question in Q&A
Discussion options

You must be logged in to vote

重定向print

可以参考 https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python , 大概能想到3种方案。

import io
import subprocess
from contextlib import redirect_stdout

from pywebio import start_server
from pywebio.output import *


def main():
    # 方案一,最简单
    f = io.StringIO()
    with redirect_stdout(f):
        print('test')
    s = f.getvalue()
    put_text(s)

    # 方案二,支持实时输出
    class WebIO(io.IOBase):
        def write(self, bytes):
            put_text(bytes, inline=True)

    with redirect_stdout(WebIO()):
        print('test')

    # 方案三,支持脚本输出重定向
    # 谷歌搜索 "python subprocess capture output real time" 就可以得到以下方案
    process = subprocess.Popen("ls -ahl", shell=True, stdout=

Replies: 3 comments 4 replies

Comment options

You must be logged in to vote
2 replies
@wang0618
Comment options

@wang0618
Comment options

Answer selected by wang0618
Comment options

You must be logged in to vote
2 replies
@wang0618
Comment options

@lifeofpi2012
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants