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服务器已关闭。")

回车键退出服务器

相关推荐
柴 基2 小时前
Jupyter Notebook 使用指南
ide·python·jupyter
Python×CATIA工业智造3 小时前
Pycaita二次开发基础代码解析:几何体重命名与参数提取技术
python·pycharm·pycatia
你的电影很有趣4 小时前
lesson30:Python迭代三剑客:可迭代对象、迭代器与生成器深度解析
开发语言·python
-SGlow-4 小时前
MySQL相关概念和易错知识点(3)(表内容的CURD、内置函数)
linux·运维·服务器·数据库·mysql
编程社区管理员5 小时前
Vue项目使用ssh2-sftp-client实现打包自动上传到服务器(完整教程)
运维·服务器·vue
不搞学术柒柒5 小时前
vscode、cursor无密码ssh远程连接服务器(配置密钥)
服务器·ssh·github
成成成成成成果6 小时前
揭秘动态测试:软件质量的实战防线
python·功能测试·测试工具·测试用例·可用性测试
cpsvps6 小时前
文件系统完整性校验工具在美服安全审计中的关键作用与实施步骤
服务器·网络·架构
sz66cm6 小时前
Linux基础 -- 内核快速向用户态共享内核变量方案之ctl_table
linux·运维·服务器