采用Socket方式,启动时占用一个端口,转化问题为判断端口是不是存在?
import sys
import locale
import http.server
import socketserver
import requests
import threading
from time import sleep addr = 'localhost'
port = def BindHttp():
handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer((addr, port), handler)
print("HTTP server is at: http://%s:%d/" % (addr, port))
httpd.serve_forever()
def CheckRunning():
tempUrl = 'http://' + addr + ':' + str(port)
try:
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/49.0.2')]
opener.open(tempUrl)
print('验证端口'+str(port)+'启动正常!')
return True
except urllib.error.HTTPError:
# print('验证端口' + str(port) + '没有启动!错误代码:HTTPError')
print('验证端口' + str(port) + '没有启动!')
return False
except urllib.error.URLError:
# print('验证端口' + str(port) + '没有启动!错误代码:URLError')
print('验证端口' + str(port) + '没有启动!')
return False
if __name__ == '__main__': t = threading.Thread(target=BindHttp) t.setDaemon(True) t.start() print(CheckRunning()) input("\n\nPress the enter key to exit.")