python实现http文件服务器访问下载

//1.py

python 复制代码
import http.server
import socketserver
import os
import threading
import sys

# 获取当前脚本所在的目录
DIRECTORY = os.path.dirname(os.path.abspath(__file__))

# 设置服务器的端口
PORT = 8000

# 自定义Handler,将根目录设置为脚本所在目录
class MyHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

# 创建服务器对象
httpd = socketserver.TCPServer(("", PORT), MyHTTPRequestHandler)

# 定义一个函数,用于监听键盘输入
def wait_for_quit():
    input("按任意键退出服务...\n")
    print("正在关闭服务器...")
    httpd.shutdown()  # 关闭服务器
    httpd.server_close()  # 释放端口
    print("服务器已关闭。")
    sys.exit(0)  # 退出程序

# 启动服务器
print(f"服务器已启动,访问地址: http://<电脑的IP地址>:{PORT}")
print(f"服务器根目录: {DIRECTORY}")

# 启动一个线程来监听键盘输入
quit_thread = threading.Thread(target=wait_for_quit)
quit_thread.daemon = True  # 设置为守护线程,主线程退出时自动结束
quit_thread.start()

# 启动服务器主循环
try:
    httpd.serve_forever()
except KeyboardInterrupt:
    print("\n服务器已关闭。")

回车键退出服务器

相关推荐
星空椰9 小时前
Python 面向对象高级:继承与类定义详解
开发语言·python
凯瑟琳.奥古斯特10 小时前
高阶子查询题目精炼
开发语言·数据库·python·职场和发展·数据库开发
lolo大魔王10 小时前
Linux 文件系统超全面详解(原理、结构、挂载、分区、inode、日志、管理命令)
linux·运维·服务器
风之所往_10 小时前
Python 3.4 新特性全面总结
python
太阳上的雨天11 小时前
任何格式的文件转Markdown
python·ai
yaoxin52112311 小时前
419. 现代 Java IO 最佳实践 - 写入文本文件
java·windows·python
weixin_4684668511 小时前
纳米 AI 搜索新手极速上手指南
人工智能·python·深度学习·搜索引擎·ai·语言模型·自然语言处理
凯瑟琳.奥古斯特11 小时前
数据库原理选择题精选
数据库·python·职场和发展
彦为君12 小时前
JavaSE-07-异常机制
java·开发语言·后端·python·spring