3

I'm trying to integrate l2ping with Python (2.7). l2ping is a tool from blueZ package, running on linux, that performs echo request to a bluetooth device.

I want to show (or store in a variable) the output of the echo request in real time.

I have read a lot of discussion in this community, but (in my case) all the solutions show the result only at the end of the pinging process.

This is my code:

#!/usr/bin/python
import subprocess

mac_addr=  'XX:XX:XX:XX:XX:XX' //my real bluetooth mac address
process = subprocess.Popen(['unbuffer', 'l2ping', '-c', '3', mac_addr], bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

while True:
    print "debug"
    line = process.stdout.readline()
    if not line:
        break
    else:
        print line

As I previously said, my code show the output but all in one time at the end of the process. The program goes till the "debug" line and then it stops, wait the end of l2ping and prints out all the output.

I've also try to use bufsize=0, or stdout.flush() but no output are shown in real time. Also, communicate() nor check_output() don't work for me.

I think that l2ping command is quite different from some others, in fact it does not write immediately on stdout and this can cause the specific problem.

What I'm doing wrong? How can I read in real time the output of l2ping?

EDIT: I've found a solution that works fine for me. I use the command unbuffer when I call l2ping. I've edit the code.

edoardesd
  • 109
  • 1
  • 8
  • Possible duplicate of [printing stdout in realtime from a subprocess that requires stdin](http://stackoverflow.com/questions/17411966/printing-stdout-in-realtime-from-a-subprocess-that-requires-stdin) – Mad Physicist May 16 '17 at 14:48
  • @MadPhysicist It isn't a duplicate, in my case the answer is not working due to the use of `l2ping` – edoardesd May 16 '17 at 15:53
  • What does `l2ping` do different from any normal process? – Mad Physicist May 16 '17 at 16:23
  • @MadPhysicist The fact that a code that works with all others process doesn't work with l2ping. If I have known the answer I don't write here... – edoardesd May 16 '17 at 17:30
  • Fair enough. So that's the question then. What makes the output of `l2ping` different? Does it itself detect that it is writing to a pipe and buffer it? Because at this point, it's the only thing I can think of. – Mad Physicist May 16 '17 at 18:02

0 Answers0