MicroPython模块执行函数语法错误:main.py报错但network.py可正常运行
MicroPython模块调用语法错误排查与解决
我在MicroPython开发中遇到一个奇怪的问题:单独运行network.py时一切正常,但通过main.py调用该模块时,却触发了指向network.py第6行的SyntaxError。试过用变量传递参数、调整返回值接收方式,都没解决问题。
相关代码
network.py
import time import network import urequests class netWireless: def setUp(ssid,password): wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid,password) max_wait = 10 while max_wait > 0: if wlan.status() < 0 or wlan.status() >= 3: break max_wait -= 1 print("waiting for connection...") time.sleep(1) if wlan.status() != 3: raise RuntimeError('network connection failed') return 0; else: print('connected') status = wlan.ifconfig() print('ip = ' + status[0]) return 1; def getJSON(url): response = urequests.get(url) json = response.json() response.close() return json; # 单独运行时可正常执行 netWireless.setUp('ssid','password')
main.py
import config import modules.network import modules.dateTime # 调用时出错 setUpStatus = netWireless.setUp('ssid','password')
错误信息
Traceback (most recent call last): File "<stdin>", line 2, in <module> File "modules/network.py", line 6 SyntaxError: invalid syntax
问题原因
- 类方法定义不符合规范:
netWireless类中的setUp和getJSON方法既没有添加实例方法必需的self参数,也没有用@staticmethod标记为静态方法,导致模块被导入时Python解析器判定语法错误。 - 模块引用路径错误:
main.py中直接使用netWireless类,但仅导入了modules.network模块,未正确指定类的访问路径。 - 模块名冲突风险:自定义模块名为
network.py,与MicroPython内置的network模块重名,可能干扰导入逻辑。
解决步骤
1. 修正类方法定义
给类中的方法添加@staticmethod装饰器,将其标记为静态方法(无需实例化即可直接调用):
import time import network import urequests class netWireless: @staticmethod def setUp(ssid,password): wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect(ssid,password) max_wait = 10 while max_wait > 0: if wlan.status() < 0 or wlan.status() >= 3: break max_wait -= 1 print("waiting for connection...") time.sleep(1) if wlan.status() != 3: raise RuntimeError('network connection failed') return 0; else: print('connected') status = wlan.ifconfig() print('ip = ' + status[0]) return 1; @staticmethod def getJSON(url): response = urequests.get(url) json = response.json() response.close() return json; # 单独运行测试可保留,模块导入时不会执行 # netWireless.setUp('ssid','password')
2. 修正main.py的引用方式
两种可选方案:
- 方案一:直接导入类
import config from modules.network import netWireless import modules.dateTime setUpStatus = netWireless.setUp('ssid','password')
- 方案二:通过模块路径访问类
import config import modules.network import modules.dateTime setUpStatus = modules.network.netWireless.setUp('ssid','password')
3. 规避模块名冲突(推荐)
将自定义的network.py重命名为wireless.py,避免与内置模块重名,同时更新main.py的导入语句:
# main.py中修改导入语句 from modules.wireless import netWireless
内容的提问来源于stack exchange,提问作者Gustavo more gaspar
相关产品推荐
相关产品推荐

