0

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

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.

Chris
  • 9,603
  • 15
  • 46
  • 67

1 Answers1

2

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

Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496
  • So that would only work if I call the process ('ls' in your example) at a specific time. I'm trying to figure out how to incorporate that strategy with my candump (which is constantly running in another thread and only dumps out data as it comes in) and am having a tough time with it. I'll keep plugging away, but if you've got any htoughts I'd love to hear them. – Chris Mar 04 '13 at 23:38
  • @Chris: Then check out the question that I linked to. – Blender Mar 04 '13 at 23:41
  • 2
    @Chris: Regarding the answer linked above, using `['stdbuf', '-oL' 'candump', 'can0']` may help if `candump` buffers its output when piped. `stdbuf -oL` attempts to make the `stdout` stream use line buffering, but it might not work. If it works, you can iterate with `iter(proc.stdout.readline, b'')`. – Eryk Sun Mar 05 '13 at 01:06