python读取esp8266的mac地址

发布时间:2024年01月18日

读取 MAC 地址并保存到文件后就退出。

确保你已经安装好了以下库

pip install esptool
pip install subprocess

下面是修改后的脚本:

import subprocess
import time
import os

print("Please connect ESP8266 to USB port...")

serial_port = 'COM3'  # Replace with the correct port

while True:
    if os.path.exists('\\\\.\\' + serial_port):
        print("Detected an ESP8266 device")
        mac_process = subprocess.run(['python', '-m', 'esptool', '--chip', 'esp8266', '--port', serial_port, 'read_mac'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        mac_output = mac_process.stdout
        
        mac = ""
        for line in mac_output.split('\n'):
            if "MAC" in line:
                mac = line.strip()
                break
        
        if mac:
            with open('maclist.txt', 'a') as f:
                f.write(mac + '\n')
                print(f"MAC {mac} has been recorded.")
            print("The program will now exit.")
            break  # Exit the loop after writing the MAC address

        else:
            print("Failed to read the MAC address.")
            break  # Exit if MAC address is not found

    else:
        print('Device is not ready...')
        # Wait a bit before trying again
        time.sleep(1)

在这个脚本中,一旦检测到设备并且成功读取并记录了 MAC 地址,break 语句会被调用来终止 while 循环,从而导致脚本结束运行。我们则可以在python脚本同目录找到保存mac地址的txt文件。

文章来源:https://blog.csdn.net/weixin_46084533/article/details/135666227
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。