I have a raspberry pi 4 model b running Raspberry Pi OS Lite 64-bit with

Operating System: Debian GNU/Linux 12 (bookworm)
Kernel: Linux 6.6.20+rpt-rpi-v8.

I have to control the Bluetooth of the raspberry with a python script. The script has to be able to enable/disable Bluetooth and rename the raspberry pi.
I need to change the Bluetooth name automatically on the fly, because the Bluetooth name has to correspond to connected devices that can be hot-swapped

Currently, I use os.system(f"sudo hostnamectl set-hostname '{name}'") to rename the device and os.system(f"sudo systemctl restart bluetooth") to restart bluetooth. This only works some of the time, and often times I manually have to enter more commands in the console:

pi@One:~ $ bluetoothctl
[bluetooth]# discoverable on
[bluetooth]# exit

Is there a more elegant solution to do this, that may also allow for more functionality?

  • This question is too vague. There never has been a 64 bit Raspbian. Why do you WANT to change hostname in a script - it could be done but not unless you change properly it will create issues; there is a perfectly good method in raspi-config.
    – Milliways
    Commented May 2 at 8:01
  • @Milliways Sorry, I meant Raspberry Pi OS lite, not raspbian. I need to change the name with a script, because the script searches for a connected device, and if it finds one, renames the Bluetooth to the device's name. The device can be hot-swapped, so I need a way to rename Bluetooth with an automated script.
    – Plat00n
    Commented May 2 at 8:16
  • To successfully change hostname you also need to edit /etc/hosts. This is what the raspi-config script does.
    – Milliways
    Commented May 2 at 11:13
  • there are more elegant and efficient ways to control Bluetooth and rename your Raspberry Pi programmatically in Python. You can achieve this using the pybluez library for Bluetooth control and the socket library for hostname manipulation. github.com/pybluez/pybluez
    – liaifat85
    Commented May 2 at 11:58


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.