Python 在树莓派上实现WIFI连接

开发语言: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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rotion_深

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值