python类boot_time()的实例源码

system_module.py 文件源码 项目:stephanie-va 作者: SlapBot 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
test_linux.py 文件源码 项目:respeaker_virtualenv 作者: respeaker 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
host.py 文件源码 项目:django-heartbeat 作者: pbs 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
            }
        }
status.py 文件源码 项目:mal 作者: chaosking121 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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]
webpagetest.py 文件源码 项目:wptagent 作者: WPO-Foundation 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
status.py 文件源码 项目:apex-sigma-plugins 作者: lu-ci 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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)
status.py 文件源码 项目:hapi 作者: mayaculpa 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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()
test_linux.py 文件源码 项目:zenchmarks 作者: squeaky-pl 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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)
test_linux.py 文件源码 项目:FancyWord 作者: EastonLee 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
interrogate.py 文件源码 项目:rvmi-rekall 作者: fireeye 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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()
sys.py 文件源码 项目:centos-base-consul 作者: zeroc0d3lab 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def _get_uptime():
            return int(time() - psutil.boot_time())
ServerCommand.py 文件源码 项目:aetros-cli 作者: aetros 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
views.py 文件源码 项目:beesly 作者: bincyber 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
status.py 文件源码 项目:apex-sigma-core 作者: lu-ci 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
test_memory_leaks.py 文件源码 项目:respeaker_virtualenv 作者: respeaker 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_boot_time(self):
        self.execute(psutil.boot_time)

    # XXX - on Windows this produces a false positive
test_linux.py 文件源码 项目:respeaker_virtualenv 作者: respeaker 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_boot_time(self):
        vmstat_value = vmstat('boot time')
        psutil_value = psutil.boot_time()
        self.assertEqual(int(vmstat_value), int(psutil_value))
test_linux.py 文件源码 项目:respeaker_virtualenv 作者: respeaker 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
test_process.py 文件源码 项目:respeaker_virtualenv 作者: respeaker 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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))
test_bsd.py 文件源码 项目:respeaker_virtualenv 作者: respeaker 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
# =====================================================================
test_bsd.py 文件源码 项目:respeaker_virtualenv 作者: respeaker 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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
# =====================================================================
system.py 文件源码 项目:ahenk 作者: Pardus-LiderAhenk 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def boot_time():
            return psutil.boot_time()
proc.py 文件源码 项目:pwndemo 作者: zh-explorer 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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()
sys_utils.py 文件源码 项目:pyom_mud 作者: bodrich 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
monitor.py 文件源码 项目:python_for_linux_system_administration 作者: lalor 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def get_boot_info():
    boot_time = datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
    return dict(boot_time=boot_time)
system.py 文件源码 项目:nixstatsagent 作者: NIXStats 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
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
sys_info.py 文件源码 项目:raspberry-pi-2 作者: LuisDiazUgena 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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])
sysinfo.py 文件源码 项目:RTask 作者: HatBoy 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 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}
sysinfo.py 文件源码 项目:treadmill 作者: Morgan-Stanley 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def up_since():
    """Returns time of last reboot."""
    return psutil.boot_time()


# pylint: disable=C0103
_collect_metadata.py 文件源码 项目:perf 作者: vstinner 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
cmdb_collector.py 文件源码 项目:ops_agent 作者: sjqzhang 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号