本文整理汇总了Python中sensors.init函数的典型用法代码示例。如果您正苦于以下问题:Python init函数的具体用法?Python init怎么用?Python init使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了init函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_detected_chips
def _get_detected_chips(): # pragma: no cover
sensors.cleanup()
sensors.init()
chips_detected = list(sensors.iter_detected_chips())
return chips_detected
示例2: __init__
def __init__(self):
self.log = logging.getLogger("fanfare")
self.log.setLevel(logging.INFO)
formatter = logging.Formatter(fmt='[%(name)s] %(message)s')
handler = logging.handlers.SysLogHandler(
facility=logging.handlers.SysLogHandler.LOG_DAEMON,
address="/dev/log")
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
self.log.addHandler(handler)
self.temp_treshold = 75
self.poll_time = 30
self.fan_control_device = '/proc/acpi/ibm/fan'
if os.getuid() != 0:
self.log.error('This program must run as root, as it needs access '
'to the fan control device %s. Exiting...',
self.fan_control_device)
sys.exit(2)
self.target_label = 'Physical id 0'
self.full_speed_on = False
self.log.info("Starting fanfare daemon")
sensors.init()
示例3: get_sensors
def get_sensors(self):
"""
collects the current temperature of CPU
and each core
"""
sensors.init()
added = []
cpu_temp_c = []
try:
for chip in sensors.iter_detected_chips():
for feature in chip:
if feature.name.startswith('temp'):
if ((feature.label.startswith('Physical') or
feature.label.startswith('CPU')) and
feature.label not in added):
self._status.add_cpu_temp(feature.get_value())
elif (feature.label.startswith('Core')
and feature.label not in added):
cpu_temp_c.append(feature.get_value())
added.append(feature.label)
except sensors.SensorsError:
pass
if cpu_temp_c:
try:
self._status.add_cpu_temp_core(cpu_temp_c)
except IndexError:
pass
sensors.cleanup()
示例4: __init__
def __init__(self):
"""Initialize"""
print("Initialize")
if os.name == "posix":
sensors.init()
self.ser = serial.Serial()
self.ser.baudrate = 9600
self.ser.port = PORT
try:
self.ser.open()
except:
print("no serial port")
if os.name == "posix":
self.chips = [[0 for feature in chip] for chip in sensors.iter_detected_chips()]
self.cores = psutil.cpu_count()
self.cpuTotal = psutil.cpu_percent()
self.cpu = [0 for cores in range(self.cores)]
self.mem = psutil.virtual_memory()
self.disk = psutil.disk_usage('/')
self.netio = psutil.net_io_counters()
self.netup = 0
self.netdw = 0
self.lastnetup = 0
self.lastnetdw = 0
self.interval = 1
示例5: getY
def getY():
sensors.init() # Inicializamos sensores
temperaturas = [] # Guarda todas las tempereturas
#detectadas
suma_total = 0 # Variable de apoyo
try:
# Recorremos todos los sensores detectados
for chip in sensors.iter_detected_chips():
a = chip
b = chip.adapter_name
if b == "PCI adapter":
print "Procesador >", a,
for core in chip:
print "",core.get_value(), "C"
# Agregamos a la lista
temperaturas.append(core.get_value())
total_tempe = len(temperaturas)
suma_total = sum(suma for suma in temperaturas)
prom = int(suma_total) / total_tempe
finally:
sensors.cleanup() # Cerramos los sensores
print "prom =>", prom
print "--------------------------------------"
if SERIAL: ser.write(str(prom)) # Enviamos el prom al arduino
return prom
示例6: process_temp
def process_temp():
print("-" * 50)
sensors.init()
critical = False
try:
for chip in sensors.ChipIterator():
for feature in sensors.FeatureIterator(chip):
subs = list(sensors.SubFeatureIterator(chip, feature))
critical = None
current = None
for sub in subs:
value = sensors.get_value(chip, sub.number)
if sub.name.endswith(b"input"):
current = value
if sub.name.endswith(b"crit"):
critical_value = value
name = sensors.get_label(chip, feature)
print("Current temp for {}: {} / {}".format(name, current,
critical_value))
if current >= critical_value:
critical = True
if critical:
play_critical()
finally:
sensors.cleanup()
示例7: check
def check(self, instance):
## Capture CPU temperature stats
dimensions = self._set_dimensions(None, instance)
sensors.init()
stats ={}
try:
for chip in sensors.iter_detected_chips():
# Only temps from ISA adpters that are deteced by lm_sensors
if (chip.adapter_name == "ISA adapter"):
for feature in chip:
if "Core" in feature.label:
name = feature.label.replace(" ", "_")
name = name.lower()
stats["cpu."+str(chip)+"."+str(name)+"_temperature"] = feature.get_value()
elif "Physical id" in feature.label:
name = feature.label.replace(" ", "_")
name = name.lower()
stats["cpu."+str(chip)+".max_temperature"] = feature.get_value()
finally:
sensors.cleanup()
for key, value in stats.iteritems():
# Writes data to monasca that will go to InfluxDB
self.gauge(key, value, dimensions)
log.debug('Collected {0} cpu temp metrics'.format(len(stats))) 1,1 Top
示例8: enable
def enable(self):
try:
sensors.init()
super(Plugin, self).enable()
except Exception:
log.warning("Plex server not available.")
return self.disable()
示例9: __init__
def __init__(self):
self.netCounters = psutil.net_io_counters(pernic=True)
sensors.init()
while True:
self.updateInfoPerSecond()
self.updateInfoPerMinute()
self.display()
示例10: get_lmsensor
def get_lmsensor(self):
"""
"""
if self._lmsensor_next_run < datetime.now():
locked = self._lock.acquire(False)
if locked == True:
try:
_lmsensor = {}
pysensors.init(config_filename=self.values["config_filename"].data)
try:
for chip in pysensors.iter_detected_chips():
_lmsensor['%s'%chip] = {}
for feature in chip:
_lmsensor['%s'%chip][feature.label] = feature.get_value()
except Exception:
logger.exception("[%s] - Exception in get_lmsensor", self.__class__.__name__)
finally:
pysensors.cleanup()
for val_id in ['temperature', 'voltage']:
for config in self.values[val_id].get_index_configs():
for chip in _lmsensor:
if config in _lmsensor[chip] :
self.values[val_id].set_data_index(config=config, data=_lmsensor[chip][config])
self._lmsensor_last = True
except Exception:
logger.exception("[%s] - Exception in get_lmsensor", self.__class__.__name__)
self._lmsensor_last = False
finally:
self._lock.release()
min_poll=99999
for val_id in ['temperature_poll', 'voltage_poll']:
if self.values[val_id].data > 0:
min_poll=min(min_poll, self.values[val_id].data)
self._lmsensor_next_run = datetime.now() + timedelta(seconds=min_poll)
示例11: fetch_sensor_data
def fetch_sensor_data():
try:
sensors.init()
data = {}
for chip in sensors.iter_detected_chips():
for feature in chip:
# log stuff we care about
if feature.label not in IGNORE_READINGS:
data[feature.label] = round(feature.get_value(), 3)
sorted_data = collections.OrderedDict(sorted(data.items()))
write_data_file(sorted_data)
if USE_REDIS:
import redis
REDIS_CONNECTION = redis.StrictRedis(host='localhost', port=6379, db=0)
write_data_redis(sorted_data)
if USE_INFLUX:
from influxdb import InfluxDBClient
INFLUX_CLIENT = InfluxDBClient('localhost', 8086, 'root', 'root', 'jarvis')
write_data_influx(sorted_data, INFLUX_CLIENT)
for name, reading in sorted_data.iteritems():
print "{0}: {1}".format(name, reading)
except Exception as exception:
print_exc()
print "Failed to get sensor data: {0}".format(exception.message)
示例12: metric_init
def metric_init(params):
global descriptors
sensors.init()
corelist = []
try:
for chip in sensors.iter_detected_chips():
if chip.prefix == CORETEMP:
for feature in chip:
if feature.label.startswith('Core'):
corelist.append("%s Temperature" % feature.label)
except:
raise
finally:
sensors.cleanup()
for core in corelist:
print 'name: %s' % core
descriptors.append({'name': core,
'call_back': temp_handler,
'time_max': 90,
'value_type': 'float',
'units': 'Celsius',
'slope': 'both',
'format': '%.2f',
'description': 'Temperature of %s' % core,
'groups': 'Node Health'})
return descriptors
示例13: __init__
def __init__(self,inits=('$','%'),aliases=None,order=None):
self.inits = inits
sensors.init()
self.readings = {}
self.prev_readings = {}
if aliases is not None:
self.aliases = aliases
self.update()
示例14: serve
def serve(port):
sensors.init()
server = Server("localhost", port)
try:
server.serve_forever()
except KeyboardInterrupt:
server.server_close()
finally:
sensors.cleanup()
示例15: getDictTemp
def getDictTemp():
result = dict()
sensors.init()
try:
for chip in sensors.iter_detected_chips():
for feature in chip:
result[str(feature.label)] = str(feature.get_value())
finally:
sensors.cleanup()
return result