i want to play either a sound, which is saved on my raspberry pi as a MP3 file or send a song from my phone over bluetooth to my Pi. So i found out, that if i run a song over bluetooth and play one from a saved MP3 file, the audio output gets disturbed and isn't able to handle both sources. My idea is, to only turn bluetooth on, if i am sure, that no sound is played from a saved MP3 file. My question: how can i turn on and off bluetooth over my Python script? I want to integrate these commands in my main programm. thanks

  • Is this what you're looking for: Turning Bluetooth on and off using Python
    – Sanders
    Jan 7, 2022 at 23:42
  • 1
    @Sanders the answer you have linked to is for Windows machines. For RPi the commands are different.
    – ukBaz
    Jan 8, 2022 at 7:55
  • @ukBaz Thank you for catching that.
    – Sanders
    Jan 8, 2022 at 20:33

1 Answer 1


The Bluetooth stack on Linux is BlueZ and they make a series of APIs available using D-Bus to interface with the Bluetooth hardware.

The documentation for the various API's is available at: https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc

If you have not used D-Bus before it can be a little bit of a learning curve. There are libraries like pydbus that try to make it more Pythonic.

The command line tool busctl can be useful to experiment with how D-Bus works with BlueZ. For example busctl tree org.bluez will show a tree of the BlueZ objects. /org/bluez/hci0 is normally the built in Bluetooth adapter on a Raspberry Pi.

The API for the Bluetooth Adapter has a Powered property that you can use to turn the power on and off.

An example of what a script might look like to toggle the power would be:

import pydbus

# DBus object paths
BLUEZ_SERVICE = 'org.bluez'
ADAPTER_PATH = '/org/bluez/hci0'

# setup dbus
bus = pydbus.SystemBus()
adapter = bus.get(BLUEZ_SERVICE, ADAPTER_PATH)

# toggle power of adapter
if adapter.Powered:
    adapter.Powered = False
    adapter.Powered = True

In a separate terminal have bluetoothctl running and it will report if the script has successfully changed the power.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.