Python psutil 模块,boot_time() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用psutil.boot_time()

项目:stephanie-va    作者:SlapBot    | 项目源码 | 文件源码
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
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
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)
项目:django-heartbeat    作者:pbs    | 项目源码 | 文件源码
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
            }
        }
项目:mal    作者:chaosking121    | 项目源码 | 文件源码
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]
项目:wptagent    作者:WPO-Foundation    | 项目源码 | 文件源码
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
项目:apex-sigma-plugins    作者:lu-ci    | 项目源码 | 文件源码
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)
项目:hapi    作者:mayaculpa    | 项目源码 | 文件源码
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()
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
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)
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
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)
项目:rvmi-rekall    作者:fireeye    | 项目源码 | 文件源码
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()
项目:centos-base-consul    作者:zeroc0d3lab    | 项目源码 | 文件源码
def _get_uptime():
            return int(time() - psutil.boot_time())
项目:aetros-cli    作者:aetros    | 项目源码 | 文件源码
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
项目:beesly    作者:bincyber    | 项目源码 | 文件源码
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
项目:apex-sigma-core    作者:lu-ci    | 项目源码 | 文件源码
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)
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_boot_time(self):
        self.execute(psutil.boot_time)

    # XXX - on Windows this produces a false positive
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_boot_time(self):
        vmstat_value = vmstat('boot time')
        psutil_value = psutil.boot_time()
        self.assertEqual(int(vmstat_value), int(psutil_value))
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
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
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
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))
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
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
# =====================================================================
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
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
# =====================================================================
项目:ahenk    作者:Pardus-LiderAhenk    | 项目源码 | 文件源码
def boot_time():
            return psutil.boot_time()
项目:pwndemo    作者:zh-explorer    | 项目源码 | 文件源码
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()
项目:pyom_mud    作者:bodrich    | 项目源码 | 文件源码
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
项目:python_for_linux_system_administration    作者:lalor    | 项目源码 | 文件源码
def get_boot_info():
    boot_time = datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
    return dict(boot_time=boot_time)
项目:nixstatsagent    作者:NIXStats    | 项目源码 | 文件源码
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
项目:raspberry-pi-2    作者:LuisDiazUgena    | 项目源码 | 文件源码
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])
项目:RTask    作者:HatBoy    | 项目源码 | 文件源码
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}
项目:treadmill    作者:Morgan-Stanley    | 项目源码 | 文件源码
def up_since():
    """Returns time of last reboot."""
    return psutil.boot_time()


# pylint: disable=C0103
项目:perf    作者:vstinner    | 项目源码 | 文件源码
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
项目:ops_agent    作者:sjqzhang    | 项目源码 | 文件源码
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
项目:jasper-modules    作者:mattcurrycom    | 项目源码 | 文件源码
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)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_boot_time(self):
        self.execute(psutil.boot_time)

    # XXX - on Windows this produces a false positive
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_boot_time(self):
        vmstat_value = vmstat('boot time')
        psutil_value = psutil.boot_time()
        self.assertEqual(int(vmstat_value), int(psutil_value))
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
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
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
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))
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
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
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
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
# =====================================================================
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
def test_boot_time(self):
        self.execute(psutil.boot_time)

    # XXX - on Windows this produces a false positive
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
def test_boot_time(self):
        vmstat_value = vmstat('boot time')
        psutil_value = psutil.boot_time()
        self.assertEqual(int(vmstat_value), int(psutil_value))
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
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
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
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))
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
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
项目:FancyWord    作者:EastonLee    | 项目源码 | 文件源码
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
# =====================================================================
项目:dotfiles    作者:gbraad    | 项目源码 | 文件源码
def _get_uptime():
            return int(time() - psutil.boot_time())
项目:rvmi-rekall    作者:fireeye    | 项目源码 | 文件源码
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)
项目:telegram-bot-framework    作者:alvarogzp    | 项目源码 | 文件源码
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
        ))
项目:black_zone    作者:zh-explorer    | 项目源码 | 文件源码
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()
项目:LinuxBashShellScriptForOps    作者:DingGuodong    | 项目源码 | 文件源码
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()
项目:LinuxBashShellScriptForOps    作者:DingGuodong    | 项目源码 | 文件源码
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
项目:LinuxBashShellScriptForOps    作者:DingGuodong    | 项目源码 | 文件源码
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