2014-04-01 108 views
0

是否有一種簡單的方法可以將每個打印命令從腳本放在網頁上而不是服務器的控制檯上?我發現你可以使用命令yield,但這似乎只適用於循環,而不適用於打印命令。燒瓶:顯示在網站而不是控制檯上打印?

我想這一點,但它不能工作了正常:/ How to continuously display Python output in a Webpage?

TypeError: can't concat bytes to str 

我額外的代碼是:

script=r'C:\scripts\module.py' 
# ... 
proc = subprocess.Popen(['script'], 

當我寫的,而不是[script]['script']得到一個空白頁面將永久加載。

回答

0

錯誤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