Skip to content

List nearby/discoverable bluetooth devices, including already paired, in Python, on Linux

An answer to this question on Stack Overflow.

Question

I'm trying to list all nearby/discoverable bluetooth devices, including those already paired, using Python on Linux.

I know how to list services for a device using its address, and can connect successfully:

services = bluetooth.find_service(address='...')

Reading the PyBluez docs I would expect any nearby device to show up if I don't specify any criteria:

"If no criteria are specified, then returns a list of all nearby services detected."

The "only" thing I need right now is to be able to list already paired devices, whether they are on, off, nearby or not. Much like the list I'm getting in All Settings --> Bluetooth in Ubuntu/Unity.

Btw, the following does not list already paired devices on my machine, even if they are on/nearby. Probably because they are not discoverable once paired:

import bluetooth
for d in bluetooth.discover_devices(flush_cache=True):
    print d

Any ideas ...?

Edit: I found and installed "bluez-tools".

bt-device --list

... gives me the information I need, i.e. addresses of added devices.

I've checked the C source, found out that this might not be as easy as I thought it would be.

Still don't know how to do this in Python ...

Edit: I think DBUS might be what I should be reading up on. Seems complicated enough. If anyone has got some code to share I would be really happy. :)

Answer

You could always execute it as a shell command and read what it returns:

import subprocess as sp
p = sp.Popen(["bt-device", "--list"], stdin=sp.PIPE, stdout=sp.PIPE, close_fds=True)
(stdout, stdin) = (p.stdout, p.stdin)
data = stdout.readlines()

Now data will include a list of all output lines which you can format and play with as you like.