2017-05-26 138 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小时内的代码,希望大家好 –