1

I would like to ask if is there a way to return to python a terminated value from terminal? For example I'm using os.system to write this line to ubuntu terminal

 cat /sys/devices/virtual/thermal/thermal_zone*/temp

to return a couple of values, and I would like to be able to access this values again in python code, is it possible?

  • you should check module [psutil](https://psutil.readthedocs.io/en/latest/) and `psutil.sensors_temperatures()` – furas Jul 28 '19 at 10:11

4 Answers4

3

os.system is being deprecated, or at least replaced by subprocess

You can capture output fairly easily with subprocess.run

result = subprocess.run(['cat', '/sys/devices/virtual/thermal/thermal_zone*/temp'], capture_output=True)
print(result.stdout)
Iain Shelvington
  • 26,159
  • 1
  • 24
  • 40
  • I tried it, but it says `unexpected keyword argument 'capture_output'` so I searched and find `stdout=PIPE, stderr=PIPE` insted of `capture_output`, but this one returns only `b' '` –  Jul 28 '19 at 07:43
1

Because you have * in command so you have to use shell=True and shell will put full name in place of *

import subprocess

process = subprocess.run('cat /sys/devices/virtual/thermal/thermal_zone*/temp', shell=True, capture_output=True)

print(process.stdout.decode())

Result on my Linux Mint:

66000
47000
furas
  • 119,752
  • 10
  • 94
  • 135
  • thanks! This one worked. without shell it inputed "`*`" not as "all" but as just a "`x`"? –  Jul 28 '19 at 07:57
0

If you're using an older version of Python(<3.5)

from subprocess import check_output
result = check_output(["cat", "/sys/devices/virtual/thermal/thermal_zone*/temp"])
print(result)
Kampi
  • 1,708
  • 15
  • 24
traintraveler
  • 321
  • 1
  • 9
0

I think your looking for something like this: Retrieving the output of subprocess.call()

example:

p = Popen(['ls', '-l'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate(b"input data that is passed to subprocess' stdin")
rc = p.returncode
James
  • 365
  • 1
  • 11