启动http Web服务器,然后打开浏览器

时间:2018-07-11 23:16:46

标签: python python-2.7 server

我试图启动一个简单的HTTP服务器,然后在默认浏览器中将其打开。我不知道我在做什么错,它要么根本不启动服务器,要么直到脚本结束就停止(不是应该永远运行吗?)。

import BaseHTTPServer, SimpleHTTPServer, webbrowser, thread
def start_server():
  httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 3600), SimpleHTTPServer.SimpleHTTPRequestHandler)
  httpd.serve_forever()
thread.start_new_thread(start_server,())
url = 'http://127.0.0.1:3600'
webbrowser.open_new(url)

2 个答案:

答案 0 :(得分:2)

只要应用程序继续运行,线程就会继续存在,如果webbrowser.open_new()没有被阻止,则浏览器将很难完成运行该应用程序,您应该做的是阻止该应用程序执行完成:

import sys
import thread
import webbrowser
import time

import BaseHTTPServer, SimpleHTTPServer

def start_server():
    httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 3600), SimpleHTTPServer.SimpleHTTPRequestHandler)
    httpd.serve_forever()

thread.start_new_thread(start_server,())
url = 'http://127.0.0.1:3600'
webbrowser.open_new(url)

while True:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        sys.exit(0)

答案 1 :(得分:0)

这是@eyllanesc使用最新的http.serverthreading模块的答案的Python 3版本

import sys
import time
import threading
import webbrowser
from http.server import HTTPServer, SimpleHTTPRequestHandler

ip = "127.0.0.1"
port = 3600
url = f"http://{ip}:{port}"


def start_server():
    server_address = (ip, port)
    httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
    httpd.serve_forever()


threading.Thread(target=start_server).start()
webbrowser.open_new(url)

while True:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        sys.exit(0)