How to intercept the stdout and output the information to web page #21
-
Hi,你好
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
重定向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=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
put_text(output.decode('utf8'), inline=True)
start_server(main, port=8080, debug=True) 脚本结束后自动关闭页面可以参考 https://stackoverflow.com/questions/23306882/javascript-close-current-window 可以尝试使用 |
Beta Was this translation helpful? Give feedback.
-
非常感谢,回复这么及时和详尽 |
Beta Was this translation helpful? Give feedback.
-
Update: 现在 v1.1 版本的 |
Beta Was this translation helpful? Give feedback.
重定向print
可以参考 https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python , 大概能想到3种方案。