Get hard drive temperature using Python

I would like to get the temperature of the hard drive using Python (under Linux). I'm currently calling hddtempwith subprocess.popen, but I call it often enough that this is a performance bottleneck in my script. I think it should be possible to do something similar to issue 4193514 ?

+5
source share
3 answers

You can run hddtemp as a daemon (-d option) and then use sockets for the request - the default port is 7634.

Edit: see the code that does this .

+5
source

, @gnibbler , ? , :

from collection import defaultdict

class CachedValue(object):
    def __init__(self):
        self.timestamp = -1
        self._value = None

    @property 
    def value(self):
        return self._value

    @value.setter 
    def value(self, val):
        self._value = val 
        self.timestamp = time.time()

    def isOld(self, seconds):
        return (time.time() - self.timestamp) >= seconds

>>> _cached = defaultdict(CachedValue)
>>> _cached['hddtemp'].isOld(10)
True
>>> _cached['hddtemp'].value = 'Foo'
>>> _cached['hddtemp'].isOld(10)
False
# (wait 10 seconds)
>>> _cached['hddtemp'].isOld(10)
True

:

def reportHDD(self):
    if self._cached['hddtemp'].isOld(10):
        self._cached['hddtemp'].value = self.getNewHDDValue()
    return self._cached['hddtemp'].value

. CachedValue memcached/redis, TTL . .

+2

, , . smartmontools , , python 2.7.6, , hdd temp /statsd, .

, python ( ), 1-2- . , , :

enter code here
#!/usr/bin/env python
import os

import subprocess

import multiprocessing

def grab_hdd_temp(hdd, queue):
  for line in subprocess.Popen(['smartctl', '-a', str('/dev/' + hdd)], stdout=subprocess.PIPE).stdout.read().split('\n'):
    if ( 'Temperature_Celsius' in line.split() ) or ('Temperature_Internal' in line.split() ):
      queue.put([hdd, line.split()[9]])

def hddtmp_dict(hdds_list):
  procs = []
  queue = multiprocessing.Queue()
  hddict={}
  for hdd in hdds_list:
    p = multiprocessing.Process(target=grab_hdd_temp, args=(hdd, queue))
    procs.append(p)
    p.start()
  for _ in procs:
    val = queue.get()
    hddict[val[0]]=val[1]
    p.join()
  return hddict

if __name__ == '__main__':
  hdds_list = [ x for x in os.listdir('/sys/block/') if x.startswith('sd') ]
  hddict = hddtmp_dict(hdds_list)
  for k in hddict:
      print(k, hddict[k])

38 2 50 , . 1.08 3.50 40- . , . proc , , fcntl , , subprocess.popen, eh.

2:22 , . , , , , .

Sorry for the kludge code. I think the buffer is the best way to go at this point, but it was a cool exercise. If you do not want to install hddtemp, and I think the best option is a buffer + above. Still trying to figure it out, and also don’t understand how to do the classes.

I hope this helps someone.

+2
source

All Articles