Gather constant output from process (Python)
Question: I have a program that generates constant output (`hcitool lescan`):

    
    
    CC:41:00:4D:AA:AA Name1
    CC:41:00:4D:AA:BB Name2
    CC:41:00:4D:AA:CC Name3
    

I would like to parse this output in `Python` constantly, but **after few
seconds I want to kill the process**. As it has to be terminated manually (by
pressing `CTRL-C`), I cannot use `subprocess.check_value(["prog"])`. Also
calling `p = subprocess.Popen(["prog"], stdout=subprocess.PIPE)` isn't good,
as it orders `Popen` to read this to the `EOF`. Also, such call hangs the
`Python` script.

My question is: How can I start a program in `Python` (can be limited to
`Linux` environment) and terminate it after few seconds while gathering it's
output (from `stdout`)?


Answer: Depending on what your program is doing, you could use a couple of methods.

The first one would be to put the process in a while loop and check for the
MAC address in the lescan output file.

    
    
    import os
    
    tag = 0
    while tag != "00:11:22:33:44:55":
        open("file.txt","w").close()
        os.system("hcitool lescan> file.txt"+" & pkill --signal SIGINT hcitool")
        f = open("file.txt","r")
        read = f.read()
        if "00:11:22:33:44:55" in read:
            print "found"
            tag = "00:11:22:33:44:55"
    print "program finished"
    os._exit(0)
    

The second solution would be if you are using `lescan` and `hcidump` at the
same time.

    
    
    import time
    import os
    import subprocess
    
    d = subprocess.Popen(["sudo hcitool lescan --duplicates & sudo hcidump -w dump.txt"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
    time.sleep(3)
    dump = os.system("sudo hcidump -r dump.txt>scan.txt")
    #read the file like the previous solution I shown you
    print "program finished"
    os._exit(0)
    

The best way I found to do this was to output your readings to a file and the
scan the file for any specific thing your are looking for.

Comment back if you need anything specific, though I think I have covered your
question.

