开发语言:Python
硬件环境:树莓派 4B
运行环境:Raspberry Pi OS 64-bit
连接WIFI还是比较简单的,用了好几个Python 库都效果不怎么理想,最后还是使用命令的方式是最自在的
先断开当前的连接 wlan0 可以替换成你当前设备的网卡
ssid和pwd 可以通过入参的方式传进来
# 先断开连接cmd = "sudo nmcli device disconnect wlan0"print(cmd)# 使用subprocess模块执行命令try:output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)print("disconnect Command executed successfully:")print(output.decode('utf-8'))except subprocess.CalledProcessError as e:print("disconnect Command execution failed:")print(e.output.decode('utf-8'))command = f"sudo nmcli device wifi connect {ssid} password {psw}"print(command)# 使用subprocess模块执行命令res=""try:output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)res=output.decode('utf-8')print("connect Command executed successfully:")print(output.decode('utf-8'))except subprocess.CalledProcessError as e:print("connect Command execution failed:")print(e.output.decode('utf-8'))res=output.decode('utf-8')if("成功" in res):return BaseResult(True,res)else:return BaseResult(False,res)