You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将树莓派蓝牙扫描终端命令转换为Python 3脚本?

Hey there! Converting those interactive bluetoothctl commands into a Python 3 script is totally doable—we just need to handle the interactive session properly since bluetoothctl doesn’t run as a one-and-done command. Here’s a working solution:

Python Script for Bluetooth Device Scanning

import subprocess
import time

def scan_bluetooth_devices():
    # Launch bluetoothctl with sudo privileges
    bt_session = subprocess.Popen(
        ["sudo", "bluetoothctl"],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )

    # Send "agent on" to enable the agent
    bt_session.stdin.write("agent on\n")
    bt_session.stdin.flush()
    time.sleep(1)  # Give the system a moment to process the command

    # Start scanning for devices
    bt_session.stdin.write("scan on\n")
    bt_session.stdin.flush()

    # Let the scan run for 10 seconds (adjust this value as needed)
    print("Scanning for Bluetooth devices... Press Ctrl+C to stop early.")
    try:
        time.sleep(10)
        # Cleanly stop the scan and exit the session
        bt_session.stdin.write("scan off\nexit\n")
        bt_session.stdin.flush()
    except KeyboardInterrupt:
        # Handle user interrupt to stop scanning gracefully
        print("\nStopping scan...")
        bt_session.stdin.write("scan off\nexit\n")
        bt_session.stdin.flush()

    # Capture and display the results
    output, errors = bt_session.communicate()
    print("\nScan Results:")
    print(output)
    if errors:
        print("\nEncountered errors:")
        print(errors)

if __name__ == "__main__":
    scan_bluetooth_devices()

What’s Going On Here?

  • Interactive Session Handling: We use subprocess.Popen instead of subprocess.run() because we need to send multiple commands to the same bluetoothctl session over time, not just run a single command.
  • Text Mode: text=True makes sure we’re working with strings instead of raw bytes, which simplifies reading/writing input/output.
  • Flushing Input: After writing each command to stdin, we call flush() to ensure the command is sent immediately to the bluetoothctl process.
  • Graceful Cleanup: We include a timeout (10 seconds by default) and handle Ctrl+C so we can stop the scan and exit bluetoothctl properly instead of leaving the process hanging.

Important Notes

  • Run with Sudo: Since the original commands require sudo, you’ll need to run the script with root privileges: sudo python3 bluetooth_scan.py.
  • Adjust Scan Duration: Change the time.sleep(10) value to make the scan run longer or shorter. If you want to scan indefinitely until the user presses Ctrl+C, remove the time.sleep() call entirely.
  • Bluetooth Service Check: If you run into issues, make sure the Bluetooth service is running first. You can add this line at the start of the script to ensure it’s active:
    subprocess.run(["sudo", "systemctl", "start", "bluetooth"], check=True)
    

内容的提问来源于stack exchange,提问作者DiscreteTomatoes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:51:52