我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用psutil.boot_time()。
def tell_system_status(self): import psutil import platform import datetime os, name, version, _, _, _ = platform.uname() version = version.split('-')[0] cores = psutil.cpu_count() cpu_percent = psutil.cpu_percent() memory_percent = psutil.virtual_memory()[2] disk_percent = psutil.disk_usage('/')[3] boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()) running_since = boot_time.strftime("%A %d. %B %Y") response = "I am currently running on %s version %s. " % (os, version) response += "This system is named %s and has %s CPU cores. " % (name, cores) response += "Current disk_percent is %s percent. " % disk_percent response += "Current CPU utilization is %s percent. " % cpu_percent response += "Current memory utilization is %s percent. " % memory_percent response += "it's running since %s." % running_since return response
def test_procfs_path(self): tdir = tempfile.mkdtemp() try: psutil.PROCFS_PATH = tdir self.assertRaises(IOError, psutil.virtual_memory) self.assertRaises(IOError, psutil.cpu_times) self.assertRaises(IOError, psutil.cpu_times, percpu=True) self.assertRaises(IOError, psutil.boot_time) # self.assertRaises(IOError, psutil.pids) self.assertRaises(IOError, psutil.net_connections) self.assertRaises(IOError, psutil.net_io_counters) self.assertRaises(IOError, psutil.net_if_stats) self.assertRaises(IOError, psutil.disk_io_counters) self.assertRaises(IOError, psutil.disk_partitions) self.assertRaises(psutil.NoSuchProcess, psutil.Process) finally: psutil.PROCFS_PATH = "/proc" os.rmdir(tdir)
def check(request): return { 'hostname': socket.gethostname(), 'ips': ips, 'cpus': psutil.cpu_count(), 'uptime': timesince(datetime.fromtimestamp(psutil.boot_time())), 'memory': { 'total': filesizeformat(psutil.virtual_memory().total), 'available': filesizeformat(psutil.virtual_memory().available), 'used': filesizeformat(psutil.virtual_memory().used), 'free': filesizeformat(psutil.virtual_memory().free), 'percent': psutil.virtual_memory().percent }, 'swap': { 'total': filesizeformat(psutil.swap_memory().total), 'used': filesizeformat(psutil.swap_memory().used), 'free': filesizeformat(psutil.swap_memory().free), 'percent': psutil.swap_memory().percent } }
def sysInfoRaw(): import time import psutil cpuPercent = psutil.cpu_percent(interval=1) memPercent = psutil.virtual_memory().percent sda2Percent = psutil.disk_usage('/').percent sda3Percent = psutil.disk_usage('/home').percent seconds = int(time.time()) - int(psutil.boot_time()) m, s = divmod(seconds, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) uptime = [d, h, m, s] return [cpuPercent, memPercent, sda2Percent, sda3Percent, uptime]
def get_uptime_minutes(self): """Get the system uptime in seconds""" boot_time = None try: boot_time = psutil.boot_time() except Exception: pass if boot_time is None: try: boot_time = psutil.get_boot_time() except Exception: pass if boot_time is None: try: boot_time = psutil.BOOT_TIME except Exception: pass uptime = None if boot_time is not None and boot_time > 0: uptime = int((time.time() - boot_time) / 60) if uptime is not None and uptime < 0: uptime = 0 return uptime # pylint: enable=E1101
def status(cmd, message, args): os_icon, os_color = get_os_icon() general_text = f'Latency: **{int(cmd.bot.latency * 1000)}ms**' general_text += f'\nPlatform: **{sys.platform.upper()}**' general_text += f'\nStarted: **{arrow.get(psutil.boot_time()).humanize()}**' cpu_clock = psutil.cpu_freq() if cpu_clock: cpu_clock = cpu_clock.current else: cpu_clock = 'Unknown' cpu_text = f'Count: **{psutil.cpu_count()} ({psutil.cpu_count(logical=False)})**' cpu_text += f'\nUsage: **{psutil.cpu_percent()}%**' cpu_text += f'\nClock: **{cpu_clock} MHz**' used_mem = humanfriendly.format_size(psutil.virtual_memory().available, binary=True) total_mem = humanfriendly.format_size(psutil.virtual_memory().total, binary=True) mem_text = f'Used: **{used_mem}**' mem_text += f'\nTotal: **{total_mem}**' mem_text += f'\nPercent: **{int(100 - psutil.virtual_memory().percent)}%**' response = discord.Embed(color=os_color) response.set_author(name=socket.gethostname(), icon_url=os_icon) response.add_field(name='General', value=general_text) response.add_field(name='CPU', value=cpu_text) response.add_field(name='Memory', value=mem_text) await message.channel.send(embed=response)
def update(self): """Function to update the entire class information.""" self.cpu["percentage"] = psutil.cpu_percent(interval=0.7) self.boot = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime( "%Y-%m-%d %H:%M:%S") virtual_memory = psutil.virtual_memory() self.memory["used"] = virtual_memory.used self.memory["free"] = virtual_memory.free self.memory["cached"] = virtual_memory.cached net_io_counters = psutil.net_io_counters() self.network["packet_sent"] = net_io_counters.packets_sent self.network["packet_recv"] = net_io_counters.packets_recv disk_usage = psutil.disk_usage('/') self.disk["total"] = int(disk_usage.total/1024) self.disk["used"] = int(disk_usage.used/1024) self.disk["free"] = int(disk_usage.free/1024) self.timestamp = time.time()
def run(self, flow_obj=None): if not self.is_active(): return [] if not self._config.client.writeback.client_id: self.enroll() self.startup_message.update( client_id=self._config.client.writeback.client_id, boot_time=psutil.boot_time(), agent_start_time=START_TIME, timestamp=time.time(), system_info=agent.Uname.from_current_system(session=self._session), public_key=self._config.client.writeback.private_key.public_key(), ) self.startup_message.send_message()
def _get_uptime(): return int(time() - psutil.boot_time())
def collect_system_information(self): values = {} mem = psutil.virtual_memory() values['memory_total'] = mem.total import cpuinfo cpu = cpuinfo.get_cpu_info() values['resources_limit'] = self.resources_limit values['cpu_name'] = cpu['brand'] values['cpu'] = [cpu['hz_advertised_raw'][0], cpu['count']] values['nets'] = {} values['disks'] = {} values['gpus'] = {} values['boot_time'] = psutil.boot_time() try: for gpu_id, gpu in enumerate(aetros.cuda_gpu.get_ordered_devices()): gpu['available'] = gpu_id in self.enabled_gpus values['gpus'][gpu_id] = gpu except Exception: pass for disk in psutil.disk_partitions(): try: name = self.get_disk_name(disk[1]) values['disks'][name] = psutil.disk_usage(disk[1]).total except Exception: # suppress Operation not permitted pass try: for id, net in psutil.net_if_stats().items(): if 0 != id.find('lo') and net.isup: self.nets.append(id) values['nets'][id] = net.speed or 1000 except Exception: # suppress Operation not permitted pass return values
def service_info(): """ Returns information about this microservice such as name, version, and metadata about the server it is running on. """ total_memory_mb = "%d MB" % (psutil.virtual_memory().total / (1024 * 1024)) system_uptime = round((time.time() - psutil.boot_time()), 3) app_uptime = round((time.time() - psutil.Process().create_time()), 3) response_body = { 'app': { 'name': app.config['APP_NAME'], 'version': app.config['APP_VERSION'], 'uptime': app_uptime }, 'system': { "hostname": socket.gethostname(), 'processors': psutil.cpu_count(), 'memory': total_memory_mb, 'uptime': system_uptime, } } try: response_body["aws"] = get_ec2_metadata() except: pass return jsonify(response_body), 200
def status(cmd, message, args): os_icon, os_color = get_os_icon() general_text = f'Latency: **{int(cmd.bot.latency * 1000)}ms**' general_text += f'\nPlatform: **{sys.platform.upper()}**' general_text += f'\nStarted: **{arrow.get(psutil.boot_time()).humanize()}**' cpu_clock = psutil.cpu_freq() if cpu_clock: cpu_clock = cpu_clock.current else: cpu_clock = 'Unknown' cpu_text = f'Count: **{psutil.cpu_count()} ({psutil.cpu_count(logical=False)})**' cpu_text += f'\nUsage: **{psutil.cpu_percent()}%**' cpu_text += f'\nClock: **{cpu_clock} MHz**' avail_mem = psutil.virtual_memory().available total_mem = psutil.virtual_memory().total used_mem = humanfriendly.format_size(total_mem - avail_mem, binary=True) total_mem = humanfriendly.format_size(total_mem, binary=True) mem_text = f'Used: **{used_mem}**' mem_text += f'\nTotal: **{total_mem}**' mem_text += f'\nPercent: **{int(psutil.virtual_memory().percent)}%**' response = discord.Embed(color=os_color) response.set_author(name=socket.gethostname(), icon_url=os_icon) response.add_field(name='General', value=general_text) response.add_field(name='CPU', value=cpu_text) response.add_field(name='Memory', value=mem_text) if cmd.bot.cfg.dsc.bot: current_shard = message.guild.shard_id shard_latency = int(cmd.bot.latencies[current_shard][1] * 1000) verbose_description = f'Shard: #{current_shard} | ' verbose_description += f'Latency: {shard_latency}ms | ' verbose_description += f'Queue: {cmd.bot.queue.queue.qsize()}' response.description = verbose_description await message.channel.send(embed=response)
def test_boot_time(self): self.execute(psutil.boot_time) # XXX - on Windows this produces a false positive
def test_boot_time(self): vmstat_value = vmstat('boot time') psutil_value = psutil.boot_time() self.assertEqual(int(vmstat_value), int(psutil_value))
def test_boot_time_mocked(self): with mock.patch('psutil._pslinux.open', create=True) as m: self.assertRaises( RuntimeError, psutil._pslinux.boot_time) assert m.called
def create_time(self, ret, proc): try: self.assertGreaterEqual(ret, 0) except AssertionError: if OPENBSD and proc.status == psutil.STATUS_ZOMBIE: pass else: raise # this can't be taken for granted on all platforms # self.assertGreaterEqual(ret, psutil.boot_time()) # make sure returned value can be pretty printed # with strftime time.strftime("%Y %m %d %H:%M:%S", time.localtime(ret))
def test_boot_time(self): s = sysctl('sysctl kern.boottime') s = s[s.find(" sec = ") + 7:] s = s[:s.find(',')] btime = int(s) self.assertEqual(btime, psutil.boot_time()) # ===================================================================== # --- OpenBSD # =====================================================================
def test_boot_time(self): s = sysctl('kern.boottime') sys_bt = datetime.datetime.strptime(s, "%a %b %d %H:%M:%S %Y") psutil_bt = datetime.datetime.fromtimestamp(psutil.boot_time()) self.assertEqual(sys_bt, psutil_bt) # ===================================================================== # --- NetBSD # =====================================================================
def boot_time(): return psutil.boot_time()
def starttime(pid): """starttime(pid) -> float Arguments: pid (int): PID of the process. Returns: The time (in seconds) the process started after system boot """ return psutil.Process(pid).create_time() - psutil.boot_time()
def __init__(self): sysmem = psutil.virtual_memory() proc = psutil.Process() proc_io = proc.io_counters() proc_mem = proc.memory_info() self._time = time.time() self._boot_time = psutil.boot_time() self._sysmem_available = sysmem.available self._sysmem_total = sysmem.total self._sysmem_percent = sysmem.percent self._proc_create_time = proc.create_time() self._proc_rss = proc_mem.rss self._proc_io_read = proc_io.read_count self._proc_io_write = proc_io.write_count
def get_boot_info(): boot_time = datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") return dict(boot_time=boot_time)
def run(self, *unused): systeminfo = {} cpu = {} if(os.path.isfile("/proc/cpuinfo")): f = open('/proc/cpuinfo') if f: for line in f: # Ignore the blank line separating the information between # details about two processing units if line.strip(): if "model name" == line.rstrip('\n').split(':')[0].strip(): cpu['brand'] = line.rstrip('\n').split(':')[1].strip() if "Processor" == line.rstrip('\n').split(':')[0].strip(): cpu['brand'] = line.rstrip('\n').split(':')[1].strip() if "processor" == line.rstrip('\n').split(':')[0].strip(): cpu['count'] = line.rstrip('\n').split(':')[1].strip() else: cpu['brand'] = "Unknown CPU" cpu['count'] = 0 mem = psutil.virtual_memory() if sys.platform == "linux" or sys.platform == "linux2": systeminfo['os'] = str(' '.join(platform.linux_distribution())) elif sys.platform == "darwin": systeminfo['os'] = "Mac OS %s" % platform.mac_ver()[0] cpu['brand'] = str(systemCommand('sysctl machdep.cpu.brand_string', False)[0]).split(': ')[1] cpu['count'] = systemCommand('sysctl hw.ncpu') elif sys.platform == "freebsd10" or sys.platform == "freebsd11": systeminfo['os'] = "FreeBSD %s" % platform.release() cpu['brand'] = str(systemCommand('sysctl hw.model', False)[0]).split(': ')[1] cpu['count'] = systemCommand('sysctl hw.ncpu') elif sys.platform == "win32": systeminfo['os'] = "{} {}".format(platform.uname()[0], platform.uname()[2]) systeminfo['cpu'] = cpu['brand'] systeminfo['cores'] = cpu['count'] systeminfo['memory'] = mem.total systeminfo['psutil'] = '.'.join(map(str, psutil.version_info)) systeminfo['platform'] = platform.platform() systeminfo['uptime'] = int(time.time()-psutil.boot_time()) systeminfo['ip_addresses'] = ip_addresses() return systeminfo
def cpu_usage(): # load average, uptime uptime = datetime.now() - datetime.fromtimestamp(psutil.boot_time()) av1, av2, av3 = os.getloadavg() return "Ld:%.1f %.1f %.1f Up: %s" \ % (av1, av2, av3, str(uptime).split('.')[0])
def get_cpu(): cpu_percent = psutil.cpu_percent(interval=1, percpu=True) boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") loadavg = list() with open('/proc/loadavg', 'r') as f: lines = f.readlines() line = lines[0].split() loadavg.append(line[0]) loadavg.append(line[1]) loadavg.append(line[2]) cpu_percent = [str(cpu)+'%' for cpu in cpu_percent] return {'cpu_percent':cpu_percent, 'boot_time':boot_time, 'loadavg':loadavg}
def up_since(): """Returns time of last reboot.""" return psutil.boot_time() # pylint: disable=C0103
def collect_system_metadata(metadata): metadata['platform'] = platform.platform(True, False) if sys.platform.startswith('linux'): collect_linux_metadata(metadata) # on linux, load average over 1 minute for line in read_proc("loadavg"): fields = line.split() loadavg = fields[0] metadata['load_avg_1min'] = float(loadavg) if len(fields) >= 4 and '/' in fields[3]: runnable_threads = fields[3].split('/', 1)[0] runnable_threads = int(runnable_threads) metadata['runnable_threads'] = runnable_threads if 'load_avg_1min' not in metadata and hasattr(os, 'getloadavg'): metadata['load_avg_1min'] = os.getloadavg()[0] # Hostname hostname = socket.gethostname() if hostname: metadata['hostname'] = hostname # Boot time boot_time = None for line in read_proc("stat"): if not line.startswith("btime "): continue boot_time = int(line[6:]) break if boot_time is None and psutil: boot_time = psutil.boot_time() if boot_time is not None: btime = datetime.datetime.fromtimestamp(boot_time) metadata['boot_time'] = format_datetime(btime) metadata['uptime'] = time.time() - boot_time
def is_process_permanent(self, create_time): res = False current = time.time() boot_elapse = current - psutil.boot_time() run_time = current - create_time if boot_elapse > 60 * 15: if run_time >= 60 * 10: res = True else: if run_time >= boot_elapse * .5: res = True return res
def handle(text, mic, profile): os, name, version, _, _, _ = platform.uname() version = version.split('-')[0] cores = psutil.cpu_count() cpu_percent = psutil.cpu_percent() memory_percent = psutil.virtual_memory()[2] disk_percent = psutil.disk_usage('/')[3] boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()) running_since = boot_time.strftime("%A %d. %B %Y") response = "I am currently running on %s version %s. " %(os, version) response += "This system is named %s and has %s CPU cores. " %(name, cores) response += "Current CPU utilization is %s percent. " %cpu_percent response += "Current memory utilization is %s percent." %memory_percent mic.say(response)
def test_boot_time(self): s = sysctl('sysctl kern.boottime') s = s[s.find(" sec = ") + 7:] s = s[:s.find(',')] btime = int(s) self.assertEqual(btime, psutil.boot_time()) # --- sensors_battery
def process(self, context, ticket_location): """This method runs once on each ticket. Note that this method runs inside a threadpool. """ components = ticket_location.to_path().split("/") # Ensure the ticket location matches the ticket content. if (components[-2] != self.client_id or components[-3] != self.__class__.__name__): raise IOError("Ticket location unexpected.") # Verify the client id and public key match. if self.public_key.client_id() != self.client_id: raise crypto.CipherError("Public key incompatible with client_id") # Update the client's record by deleting the old one and inserting a new # one. context["messages"].append( dict(client_id=self.client_id, fqdn=self.system_info.fqdn, system=self.system_info.system, architecture=self.system_info.architecture, boot_time=self.boot_time, agent_start_time=self.agent_start_time, ) ) # Modify the client record atomically. self._config.server.client_record_for_server( self.client_id).read_modify_write(self._update_client_record)
def _get_system_status(self): system_uptime_value = TimeFormatter.format(self.__get_elapsed_seconds_since(psutil.boot_time())) system_uptime = FormattedText()\ .normal("Uptime: {system_uptime}").start_format().bold(system_uptime=system_uptime_value).end_format() cpu_usage_value = str(psutil.cpu_percent(interval=self.cpu_usage_sample_seconds)) + " %" cpu_usage = FormattedText()\ .normal("CPU usage: {cpu_usage} ({sample_interval} sec. sample)").start_format()\ .bold(cpu_usage=cpu_usage_value).normal(sample_interval=self.cpu_usage_sample_seconds).end_format() return FormattedText().newline().join(( FormattedText().bold("System status"), system_uptime, cpu_usage ))
def getUptime(): uptime_file = "/proc/uptime" if os.path.exists(uptime_file): with open(uptime_file, 'r') as f: return f.read().split(' ')[0].strip("\n") else: return time.time() - psutil.boot_time()
def getUptime2(): boot_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(psutil.boot_time())) print "system start at: %s" % boot_time, uptime_total_seconds = time.time() - psutil.boot_time() uptime_days = int(uptime_total_seconds / 24 / 60 / 60) uptime_hours = int(uptime_total_seconds / 60 / 60 % 24) uptime_minutes = int(uptime_total_seconds / 60 % 60) uptime_seconds = int(uptime_total_seconds % 60) print "uptime: %d days %d hours %d minutes %d seconds" % (uptime_days, uptime_hours, uptime_minutes, uptime_seconds) user_number = len(psutil.users()) print "%d user:" % user_number print " \\" for user_tuple in psutil.users(): user_name = user_tuple[0] user_terminal = user_tuple[1] user_host = user_tuple[2] user_login_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(user_tuple[3])) print " |- user online: %s, login from %s with terminal %s at %s" % ( user_name, user_host, user_terminal, user_login_time) cpu_count = psutil.cpu_count() try: with open('/proc/loadavg', 'r') as f: loadavg_c = f.read().split(' ') loadavg = dict() if loadavg_c is not None: loadavg['lavg_1'] = loadavg_c[0] loadavg['lavg_5'] = loadavg_c[1] loadavg['lavg_15'] = loadavg_c[2] loadavg['nr'] = loadavg_c[3] loadavg['last_pid'] = loadavg_c[4] print "load average: %s, %s, %s" % (loadavg['lavg_1'], loadavg['lavg_5'], loadavg['lavg_15']) if float(loadavg['lavg_15']) > cpu_count: print "Note: cpu 15 min load is high!" if float(loadavg['lavg_5']) > cpu_count: print "Note: cpu 5 min load is high!" if float(loadavg['lavg_1']) > cpu_count: print "Note: cpu 1 min load is high!" except IOError: pass
def getDmesg(): # because can NOT get data from /proc, so use 'dmesg' command to get data dmesg = subprocess.check_output(['dmesg']).split('\n') for message in dmesg: try: print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime( (float(psutil.boot_time()) + float(message.split('] ')[0][2:].strip())))), message sys.stdout.flush() except ValueError: pass