錯誤TypeError: can't concat bytes to str
意味着您使用Python 3,其中python對混合字節和Unicode字符串更爲嚴格。你也應該避免在Python 2中混合使用字節和Unicode,但是Python本身更加放鬆。
#!/usr/bin/env python3
import html
import sys
from subprocess import Popen, PIPE, STDOUT, DEVNULL
from textwrap import dedent
from flask import Flask, Response # $ pip install flask
app = Flask(__name__)
@app.route('/')
def index():
def g():
yield "<!doctype html><title>Stream subprocess output</title>"
with Popen([sys.executable or 'python', '-u', '-c', dedent("""\
# dummy subprocess
import time
for i in range(1, 51):
print(i)
time.sleep(.1) # an artificial delay
""")], stdin=DEVNULL, stdout=PIPE, stderr=STDOUT,
bufsize=1, universal_newlines=True) as p:
for line in p.stdout:
yield "<code>{}</code>".format(html.escape(line.rstrip("\n")))
yield "<br>\n"
return Response(g(), mimetype='text/html')
if __name__ == "__main__":
import webbrowser
webbrowser.open('http://localhost:23423') # show the page in browser
app.run(host='localhost', port=23423, debug=True) # run the server
另請參閱Streaming data with Python and Flask。
來源
2014-04-05 21:25:37
jfs