You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Socket服务端代码转MicroPython后在ESP32运行出现AttributeError问题求助

Python Socket服务端代码转MicroPython后在ESP32运行出现AttributeError问题求助

嘿,我来帮你排查这个问题~

你遇到的AttributeError: object has no attribute 'gethostname'是因为MicroPython的socket模块并没有实现标准Python里的socket.gethostname()方法——毕竟MicroPython是针对嵌入式设备做了精简优化的,很多桌面Python的API不会完全照搬。

你的目标是在ESP32上搭建Socket服务端接收PC发来的文本,那我们可以换两种方式来获取ESP32的IP地址,替代原来的gethostname():

方案1:直接硬编码ESP32的IP地址

先通过ESP32的WiFi连接信息(比如串口输出、路由器后台)找到它的实际IP(比如192.168.3.10),然后直接替换代码里的IP赋值行:

# Imports modules
import socket
import time

listensocket = socket.socket() # Creates an instance of socket
Port = 8000 # Port to host server on
maxConnections = 999
IP = "192.168.3.10" # 替换成你的ESP32实际IP

listensocket.bind(('', Port))

# Starts server
listensocket.listen(maxConnections)
print("Server started at " + IP + " on port " + str(Port))

# Accepts the incoming connection
(clientsocket, address) = listensocket.accept()
print("New connection made!")

running = True

while running:
    message = clientsocket.recv(1024).decode() # Gets the incoming message
    print(message)

方案2:通过network模块动态获取IP(更灵活)

如果ESP32是通过WiFi联网的,我们可以用MicroPython自带的network模块自动获取当前IP,不用硬编码:

# Imports modules
import socket
import time
import network

# 先连接WiFi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("你的WiFi名称", "你的WiFi密码")

# 等待连接成功
while not wlan.isconnected():
    time.sleep(0.5)
    print("正在连接WiFi...")

# 获取ESP32的IP地址
IP = wlan.ifconfig()[0]

listensocket = socket.socket() # Creates an instance of socket
Port = 8000 # Port to host server on
maxConnections = 999

listensocket.bind(('', Port))

# Starts server
listensocket.listen(maxConnections)
print("Server started at " + IP + " on port " + str(Port))

# Accepts the incoming connection
(clientsocket, address) = listensocket.accept()
print("New connection made!")

running = True

while running:
    message = clientsocket.recv(1024).decode() # Gets the incoming message
    print(message)

这两种方案都能解决你遇到的AttributeError问题,方案2更适合需要动态获取IP的场景,不用每次改代码。另外,你的发送端代码既然在Python和MicroPython都能正常运行,那只要服务端这边修复IP获取的问题,应该就能顺利实现PC到ESP32的文本传输啦~

备注:内容来源于stack exchange,提问作者John Dyson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 16:49:36