pythonvariablessubprocessrfcomm

How can I put result from rfcomm shell command in to a variable in python?


I am using this script in python in order to connect to a Bluetooth device and then get data, but I want to know the result of this shell command in order to do next works

import os
import time
import signal
import subprocess


p = subprocess.Popen("sudo rfcomm connect /dev/rfcomm0 XX:XX:XX:XX:XX:XX 1",shell=True)
(stderr,stdout) = p.communicate()
print 'stderr: [%s]' % stderr
print 'stdout: [%s]' % stdout
time.sleep(5)
while True:
     print "Device is ready"
     time.sleep(5)

this code is a sample when I run the command:

"sudo rfcomm connect /dev/rfcomm0 XX:XX:XX:XX:XX:XX 1" 

in shell, it returns:

Connected /dev/rfcomm0 to XX:XX:XX:XX:XX:XX on channel 1
Press CTRL-C for hangup

but how can I put above result in a variable, because I need to know the result of this command? I use stdout, stderr in subprocess but does not work. I am using python 2.7

Python subprocess and user interaction

above link talk about getting output in a variable in general, but the problem in my question related to rfcomm, which does not put its result in variable, I run those script and they works well, but it does not works when it used with rfcomm command


Solution

  • If you're using Python 3.5 or higher, you can use run instead. That way you'll have access directly like so,

    result = subprocess.run(["sudo rfcomm connect /dev/rfcomm0 XX:XX:XX:XX:XX:XX 1"], stdout=subprocess.PIPE)
    

    Then access what you want like this,

    result.stdout
    

    If ever you use Python 2.7, as suggested by documentation I linked, they redirect you to the Older high-level API section. From there you'll notice that you could use check_output

    result = subprocess.check_output(["sudo rfcomm connect /dev/rfcomm0 XX:XX:XX:XX:XX:XX 1"])
    

    Note, if ever you want to catch error also use the stderr=subprocess.STDOUT flag.

    result = subprocess.check_output("sudo rfcomm connect /dev/rfcomm0 XX:XX:XX:XX:XX:XX 1", stderr=subprocess.STDOUT, shell=True)
    

    Lasty, there is an important not you should be aware,

    By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level.

    EDIT

    Since your goal seems to get output while running. Take a look at this answer. I prefer linking instead of re-inventing the wheel.