How to use python to extract data that is pushed to stdout?
Question: I'm trying to do some scripting, but one of the utilities I have returns a
value to stdout, where I would like to assign it to a variable.

The utility (candump) is constantly running and only prints to std out when it
receives data.

    
    
    import threading
    from subprocess import call
    import time
    
    class ThreadClass(threading.Thread):
      def run(self):
        call(["candump","can0"])
    
    t = ThreadClass()
    t.start()
    time.sleep(1)
    call(["cansend", "can0", "-i", "0x601", "0x40", "0xF6", "0x60", "0x01", "0x00", "0x00", "0x00", "0x00"])
    

It returns the following values, which I would like to use in my python
script:

    
    
    <0x601> [8] 40 f6 60 01 00 00 00 00
    <0x581> [8] 4b f6 60 01 96 08 00 00
    

The documentation on candump (what is dumping the data to stdout) is
[sparse](http://git.pengutronix.de/?p=tools/canutils.git;a=blob;f=man/candump.8;h=cd11f8906500705716d0733c1b411253125e5511;hb=HEAD)

Is there I way I can tap into stdout and snatch the data going to it?

Sorry if this is incredibly obvious... learning Linux bit by bit.


Answer: If you aren't expecting a ton of output or don't mind reading it in all at
once, you can use `subprocess.check_output`:

    
    
    >>> import subprocess
    >>> print subprocess.check_output(['ls', '/etc'])
    adjtime
    adobe
    anacrontab
    apparmor.d
    arch-release
    ati
    at-spi2
    avahi
    axelrc
    bash.bash_logout
    

If you do need to read it line-by-line, take a look at this question: [read
subprocess stdout line by
line](http://stackoverflow.com/questions/2804543/read-subprocess-stdout-line-
by-line)

