python man
python man

Reputation: 15

Turning Bluetooth On/Off using python script

I want to turn my computer's Bluetooth on/off using a python script. This is what I have found on the internet so far :

import os
os.system("rfkill block bluetooth")

But it doesn't seem to work as I have a windows computer. Does anyone know the os.system() command to on/off Bluetooth? Thanks!

Upvotes: 0

Views: 5609

Answers (2)

ukBaz
ukBaz

Reputation: 7994

There is limited Bluetooth functionality available with the Windows Runtime Python Projection. Python/WinRT enables Python developers to access Windows Runtime APIs directly from Python in a natural and familiar way.

I was able to turn the Bluetooth radio off and on with the following code:

import asyncio
from winrt.windows.devices import radios


async def bluetooth_power(turn_on):
    all_radios = await radios.Radio.get_radios_async()
    for this_radio in all_radios:
        if this_radio.kind == radios.RadioKind.BLUETOOTH:
            if turn_on:
                result = await this_radio.set_state_async(radios.RadioState.ON)
            else:
                result = await this_radio.set_state_async(radios.RadioState.OFF)


if __name__ == '__main__':
    asyncio.run(bluetooth_power(False))

Upvotes: 3

armin shoughi
armin shoughi

Reputation: 64

rfkill is Linux terminal cmnd tool for enabling and disabling wireless devices, so logically that doesn't work on windows.

for working on Bluetooth with python I recommend u to use PyBluez python library

here is a sample code for read the local Bluetooth device address :

import bluetooth

if __name__ == "__main__":
   print(bluetooth.read_local_bdaddr())

Upvotes: 1

Related Questions