1

When using the terminal inside the Raspberry pi, i have to use only 3 commands to retrieve a list of Bluetooth capable devices in the area. These are the commands that are executed in order:

  • "sudo bluetoothctl"
  • "agent on"
  • "scan on"

the final command will over-time retrieve a list of scanned devices.

QUESTION: how do i translate the series of commands above into a Python 3 script using the standard subprocess module?

I Tried:

import time
import subprocess

arguments = ["sudo", "bluetoothctl"]
output = subprocess.Popen(arguments, shell=True)
time.sleep(0.1)
arguments = ["agent", "on"]
output = subprocess.Popen(arguments, shell=True)
time.sleep(0.1)
arguments = ["scan", "on"]
output = subprocess.check_output(arguments, shell=True)
time.sleep(0.1)

print(output) #not even close huh.. yea..

As you can see i'm pretty new to both Linux terminal commands and the subprocess module. Therefore any help and guidance is greatly appreciated✯

2

Isn't it args instead of arguments? And why invite problems by declaring arguments this way? And why use subprocess.Popen instead of subprocess.call? I think the latter will lead to less confusion. And why use shell=TRUE when you're getting started? And why don't you try this in the Python interpreter first to see if any of it is going to work, and not being able to see valuable feedback? Let's crawl a little before we walk :)

Try this for starters:

python3
>>> import subprocess
>>> rtnval = subprocess.call(['man', 'python']) 
>>> print (rtnval)
0
>>> 

note: type q to leave the man page

Starting the python3 interpreter will give you the >>> prompt. Type a command, hit return, and see what happens. subprocess returns a code that informs you if it executed successfully. When I print (rtnvalue), I get a 0 back, which means no error.

Lots of good references for this sort of thing... here's one

Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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