通过Python在HTML上执行时间

时间:2019-05-21 02:24:46

标签: python

我正在尝试通过Python建立网站,但是当我执行此行时:

from flask import Flask
import time
import socket

from subprocess import Popen,PIPE
from datetime import datetime
app = Flask(__name__)
host_name = {'HostName' : socket.gethostname()}
cmd = "ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'"
p = Popen(cmd, shell=True,stdout=PIPE, stderr=PIPE)
ip_address, err =  p.communicate()
ip_address = {"IP" : ip_address[:-1]}

@app.route("/")
def info():
    dateNow = {'Date' : str(time.strftime("%d/%m/%Y"))}
    timeNow = {'Time' : str(time.strftime("%H:%M:%S"))}
    return '''
<html>
    <head>
        <title>Galileo Test Page</title>
</head>
<body>
       <h1 align = "center"> Welcome to VGU </h1>
       <p align = "center"> 
           Host Name: ''' + host_name['HostName'] + '''<br> 
           IP Address: ''' + ip_address['IP'] + '''<br>
           Date: ''' + dateNow['Date'] + '''<br>
           Current time:'''+timeNow['Time']+'''<br>
</p> 
</body>
</html>
'''

网站显示错误

  

TypeError:只能将str(而不是“ bytes”)连接到str。

您能帮我解决这个问题吗?谢谢 P / s:已定义所有变量。

1 个答案:

答案 0 :(得分:0)

p.communicate()返回一个编码字符串,因此您需要对其进行解码。 此外,time.strftime将返回字符串,因此无需将其转换为字符串。

from flask import Flask
import time
import socket

from subprocess import Popen, PIPE
from datetime import datetime
app = Flask(__name__)
host_name = {'HostName': socket.gethostname()}
cmd = "ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'"
p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
ip_address, err = p.communicate()
ip_address, err = ip_address.decode(), err.decode()
ip_address = {"IP": ip_address[:-1]}


@app.route("/")
def info():
    dateNow = {'Date': time.strftime("%d/%m/%Y")}
    timeNow = {'Time': time.strftime("%H:%M:%S")}
    return '''
<html>
    <head>
        <title>Galileo Test Page</title>
</head>
<body>
       <h1 align = "center"> Welcome to VGU </h1>
       <p align = "center"> 
           Host Name: ''' + host_name['HostName'] + '''<br> 
           IP Address: ''' + ip_address['IP'] + '''<br>
           Date: ''' + dateNow['Date'] + '''<br>
           Current time:'''+timeNow['Time']+'''<br>
</p> 
</body>
</html>
'''


app.run()