Search code examples
pythonlinuxraspberry-piraspbian

Store returned linux command value into python variable


I won't lie I know this is a very easily answered question, I'm just having trouble with the documentation and given how specific I feel this is it is a little hard to find solutions online.

I'm running Raspbian on a Raspberry Pi and are attempting to write a python script that operates with the signal strength of a Bluetooth connection. In the Linux command line, if I input hcitool rssi 14:C8:9B:92:C2:05 it will return RSSI return value: 12. What I'm trying to do is store this value in a python variable in the script.

In my script I have tried both importing os, and importing subprocess modules based of the documentation I have seen online, and have tried these solutions:

var = os.system('hcitool rssi 14:C8:9B:92:C2:05')
def find_dist():
        return(os.system('hcitool rssi 14:C8:9B:92:C2:05'))
var=find_dist()
var = subprocess.call('hcitool rssi 14:C8:9B:92:C2:05', shell = true)

The os module will simply output the regular RSSI return value: 12 and print 0 for all variable values, and the subprocess module I can't really figure out the proper syntax to. I know this may seem simple, but given the specific nature I'm having trouble finding the proper documentation~

Any help would be greatly appreciated!


Solution

  • The easiest way to do that is with subprocess.run which will capture the output so you can look at it later. Here's the most simple example to get a feel for how it works:

    import subprocess
    result = subprocess.run(['echo', 'hi'], capture_output=True)
    print(result.stdout)
    

    Which will print the expected hi as the output.