读取 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文件。