2017-05-26 67 views
0

爲什麼此腳本不會將輸出打印到網頁?
它給我的:使用Flask將腳本輸出打印到網頁

*運行於http://127.0.0.1:5000/(按Ctrl + C退出)

消息,但不執行打印的網頁。

from flask import Flask 
app = Flask(__name__) 
import wmi 
ip=['server1','server2','server3','server4','server5'] 
user="username" 
password="password" 
append_services=[] 

words = 'win32' 


@app.route("/") 

def service_status(): 

    for a in ip: 
     global append_services 
     print ('\n'+a+'\n') 
     c = wmi.WMI (a,user=user,password=password) 
     get_names= c.Win32_Service() 



     for y in get_names: 
      convert = str(y.Name) 
      append_services.append(convert)   
      append_services=[w for w in append_services if w.startswith(words)] 


     for l in append_services: 
      state_of_services = c.Win32_Service(Name=l) 
      if state_of_services: 
       for x in state_of_services: 
        convert1 = str(x.State) 
        convert2 = str(x.Caption) 
        print convert1,"  ",convert2 

if __name__ == "__main__": 
    app.run() 
+2

如果使用'print',它將在控制檯上打印。如果你想在html上打印它供用戶看,你可以嘗試返回它(而不是打印,我從來沒有使用這個設置),或者將它傳遞給你的渲染模板,然後把它放到html中。 –

+0

返回在('\ n'+ a +'\ n')打印服務器名稱但返回不起作用於'convert1,','covert2' –

+0

因爲當你返回時,函數已經停止I認爲。你需要將它們都保存在一個變量中,當你退出循環時,返回它們。 –

回答

0

你需要獲得一個變量的所有結果,生成你的html然後返回,以便用戶可以看到它。讓我們試試:

from flask import Flask 
import wmi 

app = Flask(__name__) 

ip = ['server1', 'server2', 'server3', 'server4', 'server5'] 
user = "username" 
password = "password" 
append_services = [] 

words = 'win32' 


@app.route("/") 
def service_status(): 
    results = [] # Temp for result to return to html 
    for a in ip: 
     global append_services 
     print('\n'+a+'\n') 
     c = wmi.WMI(a, user=user, password=password) 
     get_names = c.Win32_Service() 

     for y in get_names: 
      convert = str(y.Name) 
      append_services.append(convert) 
      append_services = \ 
       [w for w in append_services if w.startswith(words)] 

     for l in append_services: 
      state_of_services = c.Win32_Service(Name=l) 
      if state_of_services: 
       for x in state_of_services: 
        convert1 = str(x.State) 
        convert2 = str(x.Caption) 
        results.append([a, [convert1, convert2]]) # Append results 
        print(convert1 + "  " + convert2) 

    # This part for generate HTML for return 
    html = '' 
    for i in results: 
     html += '<h2>Ip: ' + i[0] + '</br>' 
     html += '<h3>From ' + i[1][0] + ' to ' + i[1][1] 

    return html 

if __name__ == "__main__": 
    app.run() 
+0

我得到一個IP,但是當我去的URL我得到一個內部服務器錯誤。這是爲你工作嗎? –

+0

哪個URL反正,我沒有嘗試它,我只是假設你的代碼工作,並改變它導出結果 –

+0

我將測試和修復在未來24小時內的代碼,希望大家好 –