0

I am using a Temper1F sensor, the code base I am using is at https://github.com/urwen/temper. The temper.py code returns an out put as seen below.

$ python3 temper.py
Bus 001 Dev 006 413d:2107 TEMPerX_V3.3 22.6C 72.7F - - - -

I would like to take that output and put it as a string variable in a different python script. I have tried using os. How can I invoke the other python script and store the output to variable?

I have tried the following methods:

from subprocess import call
var = str(call(["python", "temper.py"]))
var2 = call(["python", "temper.py"])

import os 
os.system('python temper.py')

import temper
var = temper

The call method returns a 0.

Tim R
  • 514
  • 1
  • 8
  • 24
  • 2
    https://stackoverflow.com/questions/4760215/running-shell-command-and-capturing-the-output might be useful here. (Alternatively, I think you could use https://stackoverflow.com/questions/1218933/can-i-redirect-the-stdout-in-python-into-some-sort-of-string-buffer to redirect stdout to a string, import the other Python file, then reset stdout afterwards.) – StardustGogeta Aug 02 '19 at 16:07
  • Possible duplicate of [Running shell command and capturing the output](https://stackoverflow.com/questions/4760215/running-shell-command-and-capturing-the-output) – wjandrea Aug 02 '19 at 16:13

1 Answers1

1

Do you have no way of accessing the methods from the sensor script? That would simplify things a lot...

If not, You can use sys.stdin in your script:

import fileinput
import sys

while True:
  line = sys.stdin.readline().strip()
  if line: print "[received]: ", line

and pipe the output of the sensor script into yours:

python sensorscript.py | python yourscript.py

[edit] I've checked out the temper script, and it looks like it's pretty easy to use it as a module directly:

from temper import Temper
temper = Temper()
value = temper.read() # call this every time you want to read the sensor
bastien girschig
  • 663
  • 6
  • 26