如何将树莓派蓝牙扫描终端命令转换为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.Popeninstead ofsubprocess.run()because we need to send multiple commands to the samebluetoothctlsession over time, not just run a single command. - Text Mode:
text=Truemakes 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 callflush()to ensure the command is sent immediately to thebluetoothctlprocess. - Graceful Cleanup: We include a timeout (10 seconds by default) and handle
Ctrl+Cso we can stop the scan and exitbluetoothctlproperly 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 pressesCtrl+C, remove thetime.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
相关产品推荐
相关产品推荐

