为了账号安全,请及时绑定邮箱和手机立即绑定

在 python 代码中使用 http.server 命令行

在 python 代码中使用 http.server 命令行

潇潇雨雨 2022-12-06 15:28:12
在命令行中,我们可以这样做:$ python3 -m http.server 8674但在 Python 代码中(在 .py 中),如何做到这一点?别用os.system!我打算在 exe 中使用它,但会失败。PPS 不要建议这个。真正来自代码,而不是命令行。
查看完整描述

2 回答

?
开满天机

TA贡献1786条经验 获得超12个赞

您所要做的就是导入http.server默认模块。


from http.server import HTTPServer, SimpleHTTPRequestHandler


def run(number=8080, server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler):

    server_address = ('', number)

    httpd = server_class(server_address, handler_class)

    try:

        httpd.serve_forever()

    except KeyboardInterrupt:

        print("Exit")

有关详细说明,请参阅Python 文档



查看完整回答
反对 回复 2022-12-06
?
撒科打诨

TA贡献1934条经验 获得超2个赞

通过使用这两个模块,可以通过 Python 程序轻松地为网站提供服务:


http.server(用于 http)

套接字服务器(用于 TCP 端口)

这是工作代码的示例:


# File name:  web-server-demo.py


import http.server

import socketserver


PORT = 8080

Handler = http.server.SimpleHTTPRequestHandler


with socketserver.TCPServer(("", PORT), Handler) as httpd:

    print("serving the website at port # ", PORT)

    httpd.serve_forever()

示例 index.html 文件:


<!DOCTYPE html>

<html>

  <head>

    <title>Website served by Python</title>

  </head>

  <bod>

    <div>

      <h1>Website served by Python program</h2>

    </div>

  </body>

</html>

输出:


> python web-server-demo.py

serving the website at port #  8080

127.0.0.1 - - [25/May/2020 14:19:27] "GET / HTTP/1.1" 304 -

//img1.sycdn.imooc.com//638eef450001f53c05250294.jpg

查看完整回答
反对 回复 2022-12-06
  • 2 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信