在日常工作或局域网环境中,如果你想快速让其他设备访问你电脑上的文件,不需要搭建复杂的 FTP 或 NAS 服务器,也无需安装任何第三方软件。只需一行 Python 命令,你就能把一个目录变成可通过浏览器访问的“文件下载服务器”。
一、准备条件
1、安装了 Python(推荐 Python 3.7+)。
提示:
如果尚未安装 Python,可从官网下载并安装:
https://www.python.org
安装时,请勾选“Add python.exe to PATH”。
2、获取本机局域网 IP 地址(比如 192.168.1.3)。
提示:
可在命令行中输入以下命令来查看本机的 IP 地址。
ipconfig
macOS/Linux:ifconfig 或 ip addr
二、一行命令启动服务器
1、打开终端(命令提示符 CMD、PowerShell、或终端),输入以下命令:
python -m http.server 8000
如下图所示。
8000 是端口号,可自定义(如 8080、9000 等)。
默认共享的是当前目录。
现在,你可以在浏览器中访问这个地址:
http://localhost:8000
或在局域网其他设备访问:
http://192.168.1.3:8000
其中 192.168.1.3 可替换为你主机的局域网 IP。
提示:
在终端窗口中按 Ctrl + C 可关闭服务器。
三、在启动服务时指定目录
你可以显式指定要共享的目录,例如:
python -m http.server 8000 --directory "C:\Users\Public\Downloads"
或在 Linux/macOS 下:
python3 -m http.server 8000 --directory /home/yourname/share
四、局域网访问注意事项
1、确保你的设备和目标设备在同一局域网内。
2、如果 Windows 防火墙弹出提示,请允许“Python”通过网络通信。
3、若未弹出提示但无法访问,请手动开放端口 8000(或你设置的端口):
New-NetFirewallRule -DisplayName "Python HTTP Server" -Direction Inbound -LocalPort 8000 -Protocol TCP -Action Allow
提示:
上述命令需要“以管理员身份运行” Windows PowerShell 中执行。
五、示例脚本
你也可以保存如下 Python 脚本为 serve.py,一键启动服务。
import http.server
import socketserver
import os
PORT = 8000
DIRECTORY = "." # 以脚本文件所在的文件夹作为路径
os.chdir(DIRECTORY)
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print(f" Serving '{DIRECTORY}' at http://localhost:{PORT}")
httpd.serve_forever()
附录:
可使用以下 Python 代码获取本机局域网 IP 地址:
import socket
ip = socket.gethostbyname(socket.gethostname())
print(f"Your LAN IP is: {ip}")
“点赞有美意,赞赏是鼓励”
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.