def update(self): result = 0 if self.custom_fan is not None: try: sensors_info = self.custom_fan.split(",") sensor_major = sensors_info[0] sensor_minor = sensors_info[1] logging.debug("Fan Major " + str(sensor_major) + " Fan Minor " + str(sensor_minor)) result = psutil.sensors_fans()[sensor_major][int( sensor_minor)].current except (KeyError, IndexError, ValueError, AttributeError): result = 0 logging.debug("Fan Speend Not Available") self.is_available = False else: try: fans = psutil.sensors_fans() fan_list = list(fans.keys()) result = fans[fan_list[0]][0].current except (KeyError, IndexError, ValueError, AttributeError): result = 0 logging.debug("Fan Speend Not Available") self.is_available = False self.fan_speed = float(result) if self.fan_speed > self.max_speed: self.max_speed = self.fan_speed logging.info("Fan speed recorded" + str(self.fan_speed))
def sensorsStats(): # 返回各种设备的温度信息 # centos 上面不支持 print psutil.sensors_temperatures(fahrenheit=False) # 风扇的速度信息 print psutil.sensors_fans() # 电池的相关信息 print psutil.sensors_battery()
def discover(config, *args, **kwargs): sensors = [] if hasattr(psutil, 'sensors_battery'): unit_name = 'battery' sub_label = '' url = psutil_sensor_url(unit_name, sub_label) sensor_config = config.get(url, {}) if sensor_config.get('enabled', True) and psutil.sensors_battery(): name = sensor_config.get('name', 'Battery') sensors.append(BatterySensor(name, unit_name, sub_label)) if hasattr(psutil, 'sensors_temperatures'): temps = psutil.sensors_temperatures() for unit_name, sub_sensors in temps.items(): for sub_sensor in sub_sensors: sub_label = sub_sensor.label url = psutil_sensor_url(unit_name, sub_label) sensor_config = config.get(url, {}) if sensor_config.get('enabled', True): name = sensor_config.get('name', psutil_sensor_name(unit_name, sub_label)) sensors.append(TemperatureSensor(name, unit_name, sub_label)) if hasattr(psutil, 'sensors_fans'): fans = psutil.sensors_fans() for unit_name, sub_sensors in fans.items(): for sub_sensor in sub_sensors: sub_label = sub_sensor.label url = psutil_sensor_url(unit_name, sub_label) sensor_config = config.get(url, {}) if sensor_config.get('enabled', True): name = sensor_config.get('name', psutil_sensor_name(unit_name, sub_label)) sensors.append(FanSensor(name, unit_name, sub_label)) return sensors
async def get_sensors(fahrenheit: bool) -> dict[str, str]: """Get metrics from sensors""" temp = psutil.sensors_temperatures(fahrenheit) fans = psutil.sensors_fans() data = {"temp": "", "fans": ""} unit = "°F" if fahrenheit else "°C" t_data = [] for t_k, t_v in temp.items(): for t_item in t_v: name = t_item.label or t_k t_data.append([f"[{name}]", f"{t_item.current} {unit}"]) data["temp"] = tabulate(t_data, tablefmt="plain") or "No temperature sensors found" f_data = [] for f_k, f_v in fans.items(): for f_item in f_v: name = f_item.label or f_k f_data.append([f"[{name}]", f"{f_item.current} RPM"]) data["fans"] = tabulate(f_data, tablefmt="plain") or "No fan sensors found" return data
def get_fans_count(): active_fans_count = 0 for fans_list in psutil.sensors_fans().values(): for fan in fans_list: if fan.current > 0: active_fans_count += 1 return active_fans_count
def __init__(self): """Init sensors stats.""" # Temperatures self.init_temp = False self.stemps = {} try: # psutil>=5.1.0 is required self.stemps = psutil.sensors_temperatures() except AttributeError: logger.warning("PsUtil 5.1.0 or higher is needed to grab temperatures sensors") except OSError as e: # FreeBSD: If oid 'hw.acpi.battery' not present, Glances wont start #1055 logger.error("Can not grab temperatures sensors ({})".format(e)) else: self.init_temp = True # Fans self.init_fan = False self.sfans = {} try: # psutil>=5.2.0 is required self.sfans = psutil.sensors_fans() except AttributeError: logger.warning("PsUtil 5.2.0 or higher is needed to grab fans sensors") except OSError as e: logger.error("Can not grab fans sensors ({})".format(e)) else: self.init_fan = True # !!! Disable Fan: High CPU consumption is PSUtil 5.2.0 # Delete the following line when corrected self.init_fan = False # Init the stats self.reset()
def GET(self, **params): data = { "cpu_percent": psutil.cpu_percent(interval=1, percpu=True), "cpu_frequency": [i._asdict() for i in psutil.cpu_freq(percpu=True)], "memory": psutil.virtual_memory()._asdict(), "swap": psutil.swap_memory()._asdict() } try: t = psutil.sensors_temperatures() for k in t.keys(): for i, x in enumerate(t[k]): t[k][i] = dict(x._asdict()) data['temperatures'] = t except: logging.exception("Cannot get temperatures") try: t = psutil.sensors_fans() for k in t.keys(): for i, x in enumerate(t[k]): t[k][i] = dict(x._asdict()) data['fans'] = t except: logging.exception("Cannot get fan speeds") return data
def __init__(self): """Init sensors stats.""" # Temperatures try: # psutil>=5.1.0 is required self.stemps = psutil.sensors_temperatures() except AttributeError: logger.warning( "PsUtil 5.1.0 or higher is needed to grab temperatures sensors" ) self.initok = False self.stemps = {} else: self.initok = True # Fans try: # psutil>=5.2.0 is required self.sfans = psutil.sensors_fans() except AttributeError: logger.warning( "PsUtil 5.2.0 or higher is needed to grab fans sensors") self.sfans = {} # Init the stats self.reset()
def getTemperatures(): if not hasattr(psutil, "sensors_temperatures"): sys.exit("platform not supported") if not hasattr(psutil, "sensors_fans"): sys.exit("platform not supported") temps = psutil.sensors_temperatures() fans = psutil.sensors_fans() if not temps or not 'coretemp' in temps: sys.exit("Incompatible Hardware: Can't read any temperature") if not fans or not 'thinkpad' in fans: sys.exit("Incompatible Hardware: Can't read fan data") core0 = temps["coretemp"][0].current core1 = temps["coretemp"][1].current fan = fans["thinkpad"][0].current core0_max = temps["coretemp"][0].high core1_max = temps["coretemp"][1].high return { "core0": core0, "core1": core1, "fan": fan, "max_core0": core0_max, "max_core1": core1_max, }
def get_info(): res = {"keys": [], "temperatures": [], "fans": [], "battery": []} root_temperatures = ps.sensors_temperatures() keys_temperatures = list(root_temperatures.keys()) for i in keys_temperatures: res["keys"].append({"keys": i}) vl_temperatures = list(root_temperatures.values()) data_temperatures = list() for i in vl_temperatures: data_temperatures.append(i[0]) for sens in data_temperatures: res["temperatures"].append({ "current": sens.current, "high": sens.high or 0.0, "critical": sens.critical or 0.0 }) root_fans = ps.sensors_fans() rt_fans = list(root_fans.values()) data_fans = rt_fans[0][0] res["fans"].append({"current": data_fans.current}) data_battery = ps.sensors_battery() res["battery"].append({ "percent": data_battery.percent, "secsleft": data_battery.secsleft, "power_plugged": data_battery.power_plugged }) return res
def build_sensors_list(self, type): """Build the sensors list depending of the type. type: SENSOR_TEMP_UNIT or SENSOR_FAN_UNIT output: a list""" ret = [] if type == SENSOR_TEMP_UNIT and self.init_temp: input_list = self.stemps self.stemps = psutil.sensors_temperatures() elif type == SENSOR_FAN_UNIT and self.init_fan: input_list = self.sfans self.sfans = psutil.sensors_fans() else: return ret for chipname, chip in iteritems(input_list): i = 1 for feature in chip: sensors_current = {} # Sensor name if feature.label == '': sensors_current['label'] = chipname + ' ' + str(i) else: sensors_current['label'] = feature.label # Fan speed and unit sensors_current['value'] = int(feature.current) sensors_current['unit'] = type # Add sensor to the list ret.append(sensors_current) i += 1 return ret
def get_fan_stats(): result = {} for sysname, items in psutil.sensors_fans().items(): result.update( _prefixed_items_from_list(items, "fan_" + sysname + "_", "", {"label"})) return result
def get_fans(): if hasattr(psutil, "sensors_fans"): fans = psutil.sensors_fans() else: fans = {} return fans
def __init__(self): """Init sensors stats.""" # Temperatures self.init_temp = False self.stemps = {} try: # psutil>=5.1.0, Linux-only self.stemps = psutil.sensors_temperatures() except AttributeError: logger.debug("Cannot grab temperatures. Platform not supported.") else: self.init_temp = True # Solve an issue #1203 concerning a RunTimeError warning message displayed # in the curses interface. warnings.filterwarnings("ignore") # Fans self.init_fan = False self.sfans = {} try: # psutil>=5.2.0, Linux-only self.sfans = psutil.sensors_fans() except AttributeError: logger.debug("Cannot grab fans speed. Platform not supported.") else: self.init_fan = True # !!! Disable Fan: High CPU consumption with psutil 5.2.0 or higher # Delete the two followings lines when corrected (https://github.com/giampaolo/psutil/issues/1199) self.init_fan = False logger.debug("Fan speed sensors disable (see https://github.com/giampaolo/psutil/issues/1199)") # Init the stats self.reset()
def get_sys_info(): """ Return sys info of inxi command with injected governors information """ govs = " ".join(get_avail_gov()) sensors = { "temperatures:": psutil.sensors_temperatures(), "battery": psutil.sensors_battery(), "fans": psutil.sensors_fans() } sensors = pformat(sensors) if shutil.which("inxi") is not None: sys_info = getoutput("inxi -Fzc0") f = re.MULTILINE | re.DOTALL # remove errors at the beginning that could occur in the snap container sys_info = re.fullmatch(r"(.*)(System:.*)", sys_info, flags=f).group(2) # insert governors after "CPU:" p = re.compile(pattern=r"(.*)(CPU:)(\s+)(.+)", flags=f) indent = " " * len(p.search(sys_info).group(3)) sys_info = p.sub(fr"\1\2{indent}Governors: {govs} \4", sys_info) # insert psutil sensors after Sensors: p = re.compile(pattern=r"(.*)(Sensors:)(\s+)(.+)", flags=f) indent = " " * len(p.search(sys_info).group(3)) sys_info = p.sub(fr"\1\2{indent}\n{sensors} \4", sys_info) else: sys_info = ("Warning: inxi is not installed.\n" f"Governors: {govs}\n" f"Sensors: {sensors}\n") return sys_info
def sensors_fan(self, sensor: Optional[str] = None) -> SensorResponseList: """ Get stats from the fan sensors. :param sensor: Select the sensor name. :return: List of :class:`platypush.message.response.system.SensorFanResponse`. """ import psutil stats = psutil.sensors_fans() def _expand_stats(name, _stats): return SensorResponseList([ SensorFanResponse( name=name, current=s.current, label=s.label, ) for s in _stats ]) if sensor: stats = [addr for name, addr in stats.items() if name == sensor] assert stats, 'No such sensor name: {}'.format(sensor) return _expand_stats(sensor, stats[0]) return SensorResponseList( [_expand_stats(name, stat) for name, stat in stats.items()])
def __init__(self): """Init sensors stats.""" # Temperatures self.init_temp = False self.stemps = {} try: # psutil>=5.1.0, Linux-only self.stemps = psutil.sensors_temperatures() except AttributeError: logger.debug("Cannot grab temperatures. Platform not supported.") else: self.init_temp = True # Solve an issue #1203 concerning a RunTimeError warning message displayed # in the curses interface. warnings.filterwarnings("ignore") # Fans self.init_fan = False self.sfans = {} try: # psutil>=5.2.0, Linux-only self.sfans = psutil.sensors_fans() except AttributeError: logger.debug("Cannot grab fans speed. Platform not supported.") else: self.init_fan = True # !!! Disable Fan: High CPU consumption with psutil 5.2.0 or higher # Delete the two followings lines when corrected (https://github.com/giampaolo/psutil/issues/1199) # Correct and tested with PsUtil 5.6.1 (Ubuntu 18.04) # self.init_fan = False # logger.debug("Fan speed sensors disable (see https://github.com/giampaolo/psutil/issues/1199)") # Init the stats self.reset()
def build_sensors_list(self, type): """Build the sensors list depending of the type. type: SENSOR_TEMP_UNIT or SENSOR_FAN_UNIT output: a list""" ret = [] if type == SENSOR_TEMP_UNIT and self.init_temp: input_list = self.stemps self.stemps = psutil.sensors_temperatures() elif type == SENSOR_FAN_UNIT and self.init_fan: input_list = self.sfans self.sfans = psutil.sensors_fans() else: return ret for chipname, chip in iteritems(input_list): i = 1 for feature in chip: sensors_current = {} # Sensor name if feature.label == '': sensors_current['label'] = chipname + ' ' + str(i) else: sensors_current['label'] = feature.label # Fan speed and unit sensors_current['value'] = int(feature.current) sensors_current['unit'] = type # Add sensor to the list ret.append(sensors_current) i += 1 return ret
def test_sensors_fans(self): # Duplicate of test_system.py. Keep it anyway. for name, units in psutil.sensors_fans().items(): self.assertIsInstance(name, str) for unit in units: self.assertIsInstance(unit.label, str) self.assertIsInstance(unit.current, (float, int, type(None)))
def __init__(self): Source.__init__(self) self.name = 'Fan' self.measurement_unit = 'RPM' self.pallet = ('fan light', 'fan dark', 'fan light smooth', 'fan dark smooth') sensors_dict = dict() try: sensors_dict = psutil.sensors_fans() except (AttributeError, IOError): logging.debug("Unable to create sensors dict") self.is_available = False return if not sensors_dict: self.is_available = False return for key, value in sensors_dict.items(): sensor_name = key for sensor_idx, sensor in enumerate(value): sensor_label = sensor.label full_name = "" if not sensor_label: full_name = sensor_name + "," + str(sensor_idx) else: full_name = sensor_label logging.debug("Fan sensor name %s", full_name) self.available_sensors.append(full_name) self.last_measurement = [0] * len(self.available_sensors)
def test_sensors_fans(self): fans = psutil.sensors_fans() for name, entries in fans.items(): self.assertIsInstance(name, str) for entry in entries: self.assertIsInstance(entry.label, str) self.assertIsInstance(entry.current, (int, long)) self.assertGreaterEqual(entry.current, 0)
def sensor(): try: x=psutil.sensors_temperatures() y=psutil.sensors_fans() z=psutil.sensors_battery() return('sensor temperatures : '+str(x)+'\n'+'sensor fans: '+str(y)+'\n'+'sensors battery: '+str(z)) except requests.exceptions.HTTPError: pass
def test_sensors_fans(self): fans = psutil.sensors_fans() for name, entries in fans.items(): self.assertIsInstance(name, str) for entry in entries: self.assertIsInstance(entry.label, str) self.assertIsInstance(entry.current, (int, long)) self.assertGreaterEqual(entry.current, 0)
def status(self): disks = [p._asdict() for p in psutil.disk_partitions()] for d in disks: try: d['usage'] = psutil.disk_usage(d['mountpoint'])._asdict() except Exception: pass nic_addrs = psutil.net_if_addrs() nic_stats = psutil.net_if_stats() nics = {} for name, ctr in psutil.net_io_counters(pernic=True).items(): nics[name] = ctr._asdict() nics[name]['statistics'] = nic_stats[name]._asdict() nics[name]['addresses'] = [a._asdict() for a in nic_addrs[name]] usb = self.usb_devices freq = psutil.cpu_freq() s = { 'cpu': { 'physical_cores': psutil.cpu_count(logical=False), 'usage': psutil.cpu_percent(interval=1, percpu=True), 'loadavg': psutil.getloadavg(), 'frequency': freq._asdict() if freq else {} }, 'memory': psutil.virtual_memory()._asdict(), 'swap': psutil.swap_memory()._asdict(), 'users': [u._asdict() for u in psutil.users()], 'disks': disks, 'nics': nics, 'sensors': { 'fans': { name: [fan._asdict() for fan in fans] for name, fans in psutil.sensors_fans().items() }, 'temperatures': { name: [temp._asdict() for temp in temps] for name, temps in psutil.sensors_temperatures().items() } }, 'boottime': psutil.boot_time(), 'processes': len(psutil.pids()), 'usb': usb, 'fpga': { 'jtag_available': len([ d for d in usb if d['vendor_id'] == 0x0403 and d['product_id'] == 0x6014 ]) > 0 } } status = super().status status['status'].update(s) return status
def __init__(self): self.available = False if hasattr(psutil, "sensors_fans"): # Check if available fans_init_info = psutil.sensors_fans() if fans_init_info is not None: self.fans = [FanInfo(device_name) for device_name, sensors in fans_init_info.items()] self.available = True
def update(self): sample = psutil.sensors_fans() self.last_measurement = [] for sensor in sample.values(): for minor_sensor in sensor: # Ignore unreasonalbe fan speeds if (minor_sensor.current > 10000): continue self.last_measurement.append(int(minor_sensor.current))
def check_fan(self): # get the fans cpu_fan = psutil.sensors_fans() if len(cpu_fan) == 0: cpu_fan.update({ "Status": "Fan Sensors are not supported by the Operating System" }) return cpu_fan
def resource_usage(): platform = sys.platform proc = psutil.Process() with proc.oneshot(): cpu_usage = psutil.cpu_times_percent() mem_usage = psutil.virtual_memory() net_usage = psutil.net_io_counters() usage = { 'platform': platform, 'PID': proc.pid, 'MEM': { 'total': mem_usage.total, 'available': mem_usage.available, 'used': mem_usage.used, 'free': mem_usage.free, 'percent_used': mem_usage.percent, 'process_percent_used': proc.memory_percent() }, 'CPU': { 'user': cpu_usage.user, 'system': cpu_usage.system, 'idle': cpu_usage.idle, 'process_percent_used': proc.cpu_percent(interval=1) }, 'NET': { 'bytes_sent': net_usage.bytes_sent, 'bytes_recv': net_usage.bytes_recv, 'packets_sent': net_usage.packets_sent, 'packets_recv': net_usage.packets_recv, 'errin': net_usage.errin, 'errout': net_usage.errout, 'dropin': net_usage.dropin, 'dropout': net_usage.dropout }, 'connections': { 'ipv4': len(proc.connections('inet4')), 'ipv6': len(proc.connections('inet6')) }, 'thread_count': proc.num_threads(), 'process_count': len(psutil.pids()) } # Linux only. if platform == 'linux' or platform == 'linux2': usage['sensors'] = { 'temperatures': psutil.sensors_temperatures(), 'fans': psutil.sensors_fans() } usage['connections']['unix'] = len(proc.connections('unix')) usage['num_handles'] = proc.num_fds() elif platform == 'win32': usage['num_handles'] = proc.num_handles() return usage
def fan_stats(): data = {} if not hasattr(psutil, 'sensors_fans'): return data fans = psutil.sensors_fans() if fans: for name, entries in fans.items(): for entry in entries: data[entry.label or name] = entry.current return data
def get_fans_status(): fans = psutil.sensors_fans() return [ { 'name': sensor, 'label': fans[sensor].label, 'current': fans[sensor].current, } for sensor in fans ]
def Scan(): fans = psutil.sensors_fans() if fans != {}: print("SCAN SAYS: FAN " + str(fans)) return "1" elif fans == {}: print("SCAN SAYS2: FAN " + str(fans)) return "0" else: return "FANS, UNDEFINED"
def fan(): speed = [] data = psutil.sensors_fans() for x in data: speed.append(data[x][0].current) if len(speed) > 0: return np.average(speed) else: return 0 # rounds per minutes
def pub_hw_fan_speed(self): fans = psutil.sensors_fans() curr_time = time.time() with open("../logs/fan_speed.log", "a+") as f: for k, v in fans.items(): for fan in v: if fan.label != "": f.write("{}-{}: {}\n".format(fan.label.upper(), curr_time, fan.current)) else: f.write("{}-{}: {}\n".format(k.upper(), curr_time, fan.current))
def sensor_info(): try: tmp = psutil.sensors_temperatures() temps = {'temps': [[dict(t._asdict()) for t in tmp[item]] for item in tmp]} tmp = psutil.sensors_fans() fans = {'fans': [[dict(t._asdict()) for t in tmp[item]] for item in tmp]} battery = {'battery': dict(psutil.sensors_battery()._asdict())} return {**temps, **fans, **battery, 'status': 'SUCCESS'} except: return { 'status': 'FAILED' }
def main(): if not hasattr(psutil, "sensors_fans"): return sys.exit("platform not supported") fans = psutil.sensors_fans() if not fans: print("no fans detected") return for name, entries in fans.items(): print(name) for entry in entries: print(" %-20s %s RPM" % (entry.label or name, entry.current)) print()
def sensors_fans(): result = "" if not hasattr(psutil, "sensors_fans"): result = "sensors_fans platform not supported" return result fans = psutil.sensors_fans() if not fans: result = "no fans detected" return result for name, entries in fans.items(): result = result + name + "\n" for entry in entries: result = result + " %-20s %s RPM\n" % (entry.label or name, entry.current) result = result +"\n" return result
def main(): if hasattr(psutil, "sensors_temperatures"): temps = psutil.sensors_temperatures() else: temps = {} if hasattr(psutil, "sensors_fans"): fans = psutil.sensors_fans() else: fans = {} if hasattr(psutil, "sensors_battery"): battery = psutil.sensors_battery() else: battery = None if not any((temps, fans, battery)): print("can't read any temperature, fans or battery info") return names = set(list(temps.keys()) + list(fans.keys())) for name in names: print(name) # Temperatures. if name in temps: print(" Temperatures:") for entry in temps[name]: print(" %-20s %s°C (high=%s°C, critical=%s°C)" % ( entry.label or name, entry.current, entry.high, entry.critical)) # Fans. if name in fans: print(" Fans:") for entry in fans[name]: print(" %-20s %s RPM" % ( entry.label or name, entry.current)) # Battery. if battery: print("Battery:") print(" charge: %s%%" % round(battery.percent, 2)) if battery.power_plugged: print(" status: %s" % ( "charging" if battery.percent < 100 else "fully charged")) print(" plugged in: yes") else: print(" left: %s" % secs2hours(battery.secsleft)) print(" status: %s" % "discharging") print(" plugged in: no")
def sensors_fans(self): return psutil.sensors_fans()
def test_fans(self): if hasattr(psutil, "sensors_fans") and psutil.sensors_fans(): self.assert_stdout('fans.py') else: self.assert_syntax('fans.py')
def test_sensors_fans(self): # Duplicate of test_system.py. Keep it anyway. for name, units in psutil.sensors_fans().items(): self.assertIsInstance(name, str) for unit in units: self.assertIsInstance(unit.label, str)