Python psutil.swap_memory() Examples

The following are 30 code examples of psutil.swap_memory(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module psutil , or try the search function .
Example #1
Source File: system_status.py    From Paradrop with Apache License 2.0 12 votes vote down vote up
def getSystemInfo(cls):
        system = {
            'boot_time': psutil.boot_time(),
            'cpu_count': psutil.cpu_count(),
            'cpu_stats': psutil.cpu_stats().__dict__,
            'cpu_times': [k.__dict__ for k in psutil.cpu_times(percpu=True)],
            'disk_io_counters': psutil.disk_io_counters().__dict__,
            'disk_usage': [],
            'net_io_counters': psutil.net_io_counters().__dict__,
            'swap_memory': psutil.swap_memory().__dict__,
            'virtual_memory': psutil.virtual_memory().__dict__
        }

        partitions = psutil.disk_partitions()
        for p in partitions:
            if p.mountpoint in cls.INCLUDED_PARTITIONS:
                usage = psutil.disk_usage(p.mountpoint)
                system['disk_usage'].append({
                    'mountpoint': p.mountpoint,
                    'total': usage.total,
                    'used': usage.used
                })

        return system 
Example #2
Source File: statsd-agent.py    From dino with Apache License 2.0 7 votes vote down vote up
def memory():
    c = statsd.StatsClient(STATSD_HOST, 8125, prefix=PREFIX + 'system.memory')
    while True:
        swap = psutil.swap_memory()
        c.gauge('swap.total', swap.total)
        c.gauge('swap.used', swap.used)
        c.gauge('swap.free', swap.free)
        c.gauge('swap.percent', swap.percent)

        virtual = psutil.virtual_memory()
        c.gauge('virtual.total', virtual.total)
        c.gauge('virtual.available', virtual.available)
        c.gauge('virtual.used', virtual.used)
        c.gauge('virtual.free', virtual.free)
        c.gauge('virtual.percent', virtual.percent)
        c.gauge('virtual.active', virtual.active)
        c.gauge('virtual.inactive', virtual.inactive)
        c.gauge('virtual.buffers', virtual.buffers)
        c.gauge('virtual.cached', virtual.cached)
        time.sleep(GRANULARITY) 
Example #3
Source File: test_misc.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_serialization(self):
        def check(ret):
            if json is not None:
                json.loads(json.dumps(ret))
            a = pickle.dumps(ret)
            b = pickle.loads(a)
            self.assertEqual(ret, b)

        check(psutil.Process().as_dict())
        check(psutil.virtual_memory())
        check(psutil.swap_memory())
        check(psutil.cpu_times())
        check(psutil.cpu_times_percent(interval=0))
        check(psutil.net_io_counters())
        if LINUX and not os.path.exists('/proc/diskstats'):
            pass
        else:
            if not APPVEYOR:
                check(psutil.disk_io_counters())
        check(psutil.disk_partitions())
        check(psutil.disk_usage(os.getcwd()))
        check(psutil.users()) 
Example #4
Source File: test_aix.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_swap_memory(self):
        out = sh('/usr/sbin/lsps -a')
        # From the man page, "The size is given in megabytes" so we assume
        # we'll always have 'MB' in the result
        # TODO maybe try to use "swap -l" to check "used" too, but its units
        # are not guaranteed to be "MB" so parsing may not be consistent
        matchobj = re.search("(?P<space>\S+)\s+"
                             "(?P<vol>\S+)\s+"
                             "(?P<vg>\S+)\s+"
                             "(?P<size>\d+)MB", out)

        self.assertIsNotNone(
            matchobj, "lsps command returned unexpected output")

        total_mb = int(matchobj.group("size"))
        MB = 1024 ** 2
        psutil_result = psutil.swap_memory()
        # we divide our result by MB instead of multiplying the lsps value by
        # MB because lsps may round down, so we round down too
        self.assertEqual(int(psutil_result.total / MB), total_mb) 
Example #5
Source File: statusapi.py    From minemeld-core with Apache License 2.0 6 votes vote down vote up
def get_system_status():
    data_path = config.get('MINEMELD_LOCAL_PATH', None)
    if data_path is None:
        jsonify(error={'message': 'MINEMELD_LOCAL_PATH not set'}), 500

    res = {}
    res['cpu'] = psutil.cpu_percent(interval=1, percpu=True)
    res['memory'] = psutil.virtual_memory().percent
    res['swap'] = psutil.swap_memory().percent
    res['disk'] = psutil.disk_usage(data_path).percent
    res['sns'] = SNS_AVAILABLE

    return jsonify(result=res, timestamp=int(time.time() * 1000)) 
Example #6
Source File: test_aix.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_swap_memory(self):
        out = sh('/usr/sbin/lsps -a')
        # From the man page, "The size is given in megabytes" so we assume
        # we'll always have 'MB' in the result
        # TODO maybe try to use "swap -l" to check "used" too, but its units
        # are not guaranteed to be "MB" so parsing may not be consistent
        matchobj = re.search("(?P<space>\S+)\s+"
                             "(?P<vol>\S+)\s+"
                             "(?P<vg>\S+)\s+"
                             "(?P<size>\d+)MB", out)

        self.assertIsNotNone(
            matchobj, "lsps command returned unexpected output")

        total_mb = int(matchobj.group("size"))
        MB = 1024 ** 2
        psutil_result = psutil.swap_memory()
        # we divide our result by MB instead of multiplying the lsps value by
        # MB because lsps may round down, so we round down too
        self.assertEqual(int(psutil_result.total / MB), total_mb) 
Example #7
Source File: test_linux.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_no_vmstat_mocked(self):
        # see https://github.com/giampaolo/psutil/issues/722
        with mock_open_exception(
                "/proc/vmstat",
                IOError(errno.ENOENT, 'no such file or directory')) as m:
            with warnings.catch_warnings(record=True) as ws:
                warnings.simplefilter("always")
                ret = psutil.swap_memory()
                assert m.called
                self.assertEqual(len(ws), 1)
                w = ws[0]
                assert w.filename.endswith('psutil/_pslinux.py')
                self.assertIn(
                    "'sin' and 'sout' swap memory stats couldn't "
                    "be determined and were set to 0",
                    str(w.message))
                self.assertEqual(ret.sin, 0)
                self.assertEqual(ret.sout, 0) 
Example #8
Source File: test_sunos.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_swap_memory(self):
        out = sh('env PATH=/usr/sbin:/sbin:%s swap -l' % os.environ['PATH'])
        lines = out.strip().split('\n')[1:]
        if not lines:
            raise ValueError('no swap device(s) configured')
        total = free = 0
        for line in lines:
            line = line.split()
            t, f = line[-2:]
            total += int(int(t) * 512)
            free += int(int(f) * 512)
        used = total - free

        psutil_swap = psutil.swap_memory()
        self.assertEqual(psutil_swap.total, total)
        self.assertEqual(psutil_swap.used, used)
        self.assertEqual(psutil_swap.free, free) 
Example #9
Source File: test_misc.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_serialization(self):
        def check(ret):
            if json is not None:
                json.loads(json.dumps(ret))
            a = pickle.dumps(ret)
            b = pickle.loads(a)
            self.assertEqual(ret, b)

        check(psutil.Process().as_dict())
        check(psutil.virtual_memory())
        check(psutil.swap_memory())
        check(psutil.cpu_times())
        check(psutil.cpu_times_percent(interval=0))
        check(psutil.net_io_counters())
        if LINUX and not os.path.exists('/proc/diskstats'):
            pass
        else:
            if not APPVEYOR:
                check(psutil.disk_io_counters())
        check(psutil.disk_partitions())
        check(psutil.disk_usage(os.getcwd()))
        check(psutil.users()) 
Example #10
Source File: test_aix.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_swap_memory(self):
        out = sh('/usr/sbin/lsps -a')
        # From the man page, "The size is given in megabytes" so we assume
        # we'll always have 'MB' in the result
        # TODO maybe try to use "swap -l" to check "used" too, but its units
        # are not guaranteed to be "MB" so parsing may not be consistent
        matchobj = re.search(r"(?P<space>\S+)\s+"
                             r"(?P<vol>\S+)\s+"
                             r"(?P<vg>\S+)\s+"
                             r"(?P<size>\d+)MB", out)

        self.assertIsNotNone(
            matchobj, "lsps command returned unexpected output")

        total_mb = int(matchobj.group("size"))
        MB = 1024 ** 2
        psutil_result = psutil.swap_memory()
        # we divide our result by MB instead of multiplying the lsps value by
        # MB because lsps may round down, so we round down too
        self.assertEqual(int(psutil_result.total / MB), total_mb) 
Example #11
Source File: test_osx.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_swapmem_sout(self):
        vmstat_val = vm_stat("Pageout")
        psutil_val = psutil.swap_memory().sout
        self.assertEqual(psutil_val, vmstat_val)

    # Not very reliable.
    # def test_swapmem_total(self):
    #     out = sh('sysctl vm.swapusage')
    #     out = out.replace('vm.swapusage: ', '')
    #     total, used, free = re.findall('\d+.\d+\w', out)
    #     psutil_smem = psutil.swap_memory()
    #     self.assertEqual(psutil_smem.total, human2bytes(total))
    #     self.assertEqual(psutil_smem.used, human2bytes(used))
    #     self.assertEqual(psutil_smem.free, human2bytes(free))

    # --- network 
Example #12
Source File: test_linux.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_no_vmstat_mocked(self):
        # see https://github.com/giampaolo/psutil/issues/722
        with mock_open_exception(
                "/proc/vmstat",
                IOError(errno.ENOENT, 'no such file or directory')) as m:
            with warnings.catch_warnings(record=True) as ws:
                warnings.simplefilter("always")
                ret = psutil.swap_memory()
                assert m.called
                self.assertEqual(len(ws), 1)
                w = ws[0]
                assert w.filename.endswith('psutil/_pslinux.py')
                self.assertIn(
                    "'sin' and 'sout' swap memory stats couldn't "
                    "be determined and were set to 0",
                    str(w.message))
                self.assertEqual(ret.sin, 0)
                self.assertEqual(ret.sout, 0) 
Example #13
Source File: test_sunos.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_swap_memory(self):
        out = sh('env PATH=/usr/sbin:/sbin:%s swap -l' % os.environ['PATH'])
        lines = out.strip().split('\n')[1:]
        if not lines:
            raise ValueError('no swap device(s) configured')
        total = free = 0
        for line in lines:
            line = line.split()
            t, f = line[-2:]
            total += int(int(t) * 512)
            free += int(int(f) * 512)
        used = total - free

        psutil_swap = psutil.swap_memory()
        self.assertEqual(psutil_swap.total, total)
        self.assertEqual(psutil_swap.used, used)
        self.assertEqual(psutil_swap.free, free) 
Example #14
Source File: free.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    virt = psutil.virtual_memory()
    swap = psutil.swap_memory()
    templ = "%-7s %10s %10s %10s %10s %10s %10s"
    print(templ % ('', 'total', 'used', 'free', 'shared', 'buffers', 'cache'))
    print(templ % (
        'Mem:',
        int(virt.total / 1024),
        int(virt.used / 1024),
        int(virt.free / 1024),
        int(getattr(virt, 'shared', 0) / 1024),
        int(getattr(virt, 'buffers', 0) / 1024),
        int(getattr(virt, 'cached', 0) / 1024)))
    print(templ % (
        'Swap:', int(swap.total / 1024),
        int(swap.used / 1024),
        int(swap.free / 1024),
        '',
        '',
        '')) 
Example #15
Source File: exp_utils.py    From RegRCNN with Apache License 2.0 6 votes vote down vote up
def sysmetrics_update(self, global_step=None):
        if global_step is None:
            global_step = time.strftime("%x_%X")
        mem = psutil.virtual_memory()
        mem_used = (mem.total - mem.available)
        gpu_vals = self.gpu_logger.get_vals()
        rel_time = time.time() - self.sysmetrics_start_time
        self.sysmetrics.loc[len(self.sysmetrics)] = [global_step, rel_time,
                                                     psutil.cpu_percent(), mem_used / 1024 ** 3,
                                                     mem_used / mem.total * 100,
                                                     psutil.swap_memory().used / 1024 ** 3,
                                                     int(gpu_vals['gpu_graphics_util']),
                                                     *[torch.cuda.memory_allocated(d) / 1024 ** 3 for d in
                                                       range(torch.cuda.device_count())],
                                                     *[torch.cuda.memory_cached(d) / 1024 ** 3 for d in
                                                       range(torch.cuda.device_count())]
                                                     ]
        return self.sysmetrics.loc[len(self.sysmetrics) - 1].to_dict() 
Example #16
Source File: webapp.py    From pyrocore with GNU General Public License v2.0 6 votes vote down vote up
def json_charts(self, req):
        """ Return charting data.
        """
        disk_used, disk_total, disk_detail = 0, 0, []
        for disk_usage_path in self.cfg.disk_usage_path.split(os.pathsep):
            disk_usage = self.guarded(psutil.disk_usage, os.path.expanduser(disk_usage_path.strip()))
            if disk_usage:
                disk_used += disk_usage.used
                disk_total += disk_usage.total
                disk_detail.append((disk_usage.used, disk_usage.total))

        data = dict(
            engine      = self.json_engine(req),
            uptime      = time.time() - psutil.BOOT_TIME,  # pylint: disable=no-member
            fqdn        = self.guarded(socket.getfqdn),
            cpu_usage   = self.guarded(psutil.cpu_percent, 0),
            ram_usage   = self.guarded(psutil.virtual_memory),
            swap_usage  = self.guarded(psutil.swap_memory),
            disk_usage  = (disk_used, disk_total, disk_detail) if disk_total else None,
            disk_io     = self.guarded(psutil.disk_io_counters),
            net_io      = self.guarded(psutil.net_io_counters),
        )
        return data 
Example #17
Source File: sysinfo.py    From RTask with GNU General Public License v3.0 6 votes vote down vote up
def get_memory():
    memory = dict()
    virtual = psutil.virtual_memory()
    swap = psutil.swap_memory()
    memory['virtual_total'] = '%.2fMB' % (virtual.total/1024/1024)
    memory['virtual_available'] = '%.2fMB' % (virtual.available/1024/1024)
    memory['virtual_percent'] = str(virtual.percent)+'%'
    memory['virtual_used'] = '%.2fMB' % (virtual.used/1024/1024)
    memory['virtual_free'] = '%.2fMB' % (virtual.free/1024/1024)
    memory['virtual_active'] = '%.2fMB' % (virtual.active/1024/1024)
    memory['virtual_inactive'] = '%.2fMB' % (virtual.inactive/1024/1024)
    memory['virtual_buffers'] = '%.2fMB' % (virtual.buffers/1024/1024)
    memory['virtual_cached'] = '%.2fMB' % (virtual.cached/1024/1024)
    memory['virtual_shared'] = '%.2fMB' % (virtual.shared/1024/1024)
    memory['swap_total'] = '%.2fMB' % (swap.total/1024/1024)
    memory['swap_used'] = '%.2fMB' % (swap.used/1024/1024)
    memory['swap_free'] = '%.2fMB' % (swap.free/1024/1024)
    memory['swap_percent'] = str(swap.percent)+'%'
    memory['swap_sin'] = '%.2fMB' % (swap.sin/1024/1024)
    memory['swap_sout'] = '%.2fMB' % (swap.sout/1024/1024)
    return memory 
Example #18
Source File: test_misc.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def test_serialization(self):
        def check(ret):
            if json is not None:
                json.loads(json.dumps(ret))
            a = pickle.dumps(ret)
            b = pickle.loads(a)
            self.assertEqual(ret, b)

        check(psutil.Process().as_dict())
        check(psutil.virtual_memory())
        check(psutil.swap_memory())
        check(psutil.cpu_times())
        check(psutil.cpu_times_percent(interval=0))
        check(psutil.net_io_counters())
        if LINUX and not os.path.exists('/proc/diskstats'):
            pass
        else:
            if not APPVEYOR:
                check(psutil.disk_io_counters())
        check(psutil.disk_partitions())
        check(psutil.disk_usage(os.getcwd()))
        check(psutil.users()) 
Example #19
Source File: metrics.py    From lainonlife with MIT License 5 votes vote down vote up
def memory_metrics():
    """Get the RAM and swap usage, in bytes."""

    vminfo = psutil.virtual_memory()
    swinfo = psutil.swap_memory()

    return {
        "vm_used": vminfo[3],
        "vm_buffers": vminfo[7],
        "vm_cached": vminfo[8],
        "swap_used": swinfo[1],
        "vm_used_no_buffers_cache": vminfo[3] - vminfo[7] - vminfo[8],
    } 
Example #20
Source File: addswap.py    From WordOps with MIT License 5 votes vote down vote up
def add(self):
        """Swap addition with WordOps"""
        # Get System RAM and SWAP details
        wo_ram = psutil.virtual_memory().total / (1024 * 1024)
        wo_swap = psutil.swap_memory().total / (1024 * 1024)
        if wo_ram < 512:
            if wo_swap < 1000:
                Log.info(self, "Adding SWAP file, please wait...")

                # Install dphys-swapfile
                WOAptGet.update(self)
                WOAptGet.install(self, ["dphys-swapfile"])
                # Stop service
                WOShellExec.cmd_exec(self, "service dphys-swapfile stop")
                # Remove Default swap created
                WOShellExec.cmd_exec(self, "/sbin/dphys-swapfile uninstall")

                # Modify Swap configuration
                if os.path.isfile("/etc/dphys-swapfile"):
                    WOFileUtils.searchreplace(self, "/etc/dphys-swapfile",
                                              "#CONF_SWAPFILE=/var/swap",
                                              "CONF_SWAPFILE=/wo-swapfile")
                    WOFileUtils.searchreplace(self, "/etc/dphys-swapfile",
                                              "#CONF_MAXSWAP=2048",
                                              "CONF_MAXSWAP=1024")
                    WOFileUtils.searchreplace(self, "/etc/dphys-swapfile",
                                              "#CONF_SWAPSIZE=",
                                              "CONF_SWAPSIZE=1024")
                else:
                    with open("/etc/dphys-swapfile", 'w') as conffile:
                        conffile.write("CONF_SWAPFILE=/wo-swapfile\n"
                                       "CONF_SWAPSIZE=1024\n"
                                       "CONF_MAXSWAP=1024\n")
                # Create swap file
                WOShellExec.cmd_exec(self, "service dphys-swapfile start") 
Example #21
Source File: system_sensors.py    From system_sensors with MIT License 5 votes vote down vote up
def get_swap_usage():
    return str(psutil.swap_memory().percent) 
Example #22
Source File: sys_monitor.py    From news_spider with MIT License 5 votes vote down vote up
def _memory():
    mem_virtual = psutil.virtual_memory()
    mem_swap = psutil.swap_memory()

    contents = [_format_info('mem_virtual_total', bytes2human(mem_virtual.total)),
                _format_info('mem_virtual_free', bytes2human(mem_virtual.free)),
                _format_info('mem_virtual_percent', '%s %%' % mem_virtual.percent),
                _format_info('mem_swap_total', bytes2human(mem_swap.total)),
                _format_info('mem_swap_free', bytes2human(mem_swap.free)),
                _format_info('mem_swap_percent', '%s %%' % mem_swap.percent)]
    _print_info(contents, 'Memory') 
Example #23
Source File: undercloud_preflight.py    From python-tripleoclient with Apache License 2.0 5 votes vote down vote up
def _check_memory():
    """Check system memory

    The undercloud will not run properly in less than 8 GB of memory.
    This function verifies that at least that much is available before
    proceeding with install.
    """
    mem = psutil.virtual_memory()
    swap = psutil.swap_memory()
    total_mb = (mem.total + swap.total) / 1024 / 1024
    if total_mb < REQUIRED_MB:
        LOG.error(_('At least {0} MB of memory is required for undercloud '
                    'installation.  A minimum of 8 GB is recommended. '
                    'Only detected {1} MB').format(REQUIRED_MB, total_mb))
        raise RuntimeError(_('Insufficient memory available')) 
Example #24
Source File: stats.py    From core with GNU General Public License v3.0 5 votes vote down vote up
def get_swap():
    """Get current swap space usage."""
    s = psutil.swap_memory()
    return (int(s.used), int(s.total)) 
Example #25
Source File: ss-agent.py    From ServerSan with Apache License 2.0 5 votes vote down vote up
def swap():
    used = round(psutil.swap_memory().used / 1024.0 / 1024, 2)
    total = round(psutil.swap_memory().total / 1024.0 / 1024, 2)
    percent = psutil.swap_memory().percent
    return [used, total, percent] 
Example #26
Source File: server.py    From Adeept_RaspTank with MIT License 5 votes vote down vote up
def get_swap_info():
    """ Return swap memory  usage using psutil """
    swap_cent = psutil.swap_memory()[3]
    return str(swap_cent) 
Example #27
Source File: info.py    From Adeept_RaspTank with MIT License 5 votes vote down vote up
def get_swap_info():
    """ Return swap memory  usage using psutil """
    swap_cent = psutil.swap_memory()[3]
    return str(swap_cent) 
Example #28
Source File: system.py    From vexbot with GNU General Public License v3.0 5 votes vote down vote up
def swap(*args, **kwargs):
    swap = psutil.swap_memory()
    used = swap.used
    total = swap.total
    used = int(used/_mb_conversion)
    total = int(total/_mb_conversion)
    return 'Used: {} | Total: {}'.format(used, total) 
Example #29
Source File: system_monitor.py    From Mastering-GUI-Programming-with-Python with MIT License 5 votes vote down vote up
def refresh_stats(self):
        phys = psutil.virtual_memory()
        swap = psutil.swap_memory()
        total_mem = phys.total + swap.total
        phys_pct = (phys.used / total_mem) * 100
        swap_pct = (swap.used / total_mem) * 100

        self.data.append(
            (phys_pct, swap_pct))
        for x, (phys, swap) in enumerate(self.data):
            self.phys_set.replace(x, phys)
            self.swap_set.replace(x, swap) 
Example #30
Source File: statistics.py    From hazelcast-python-client with Apache License 2.0 5 votes vote down vote up
def _collect_swap_memory_info(self, psutil_stats, probe_total, probe_free):
        swap_info = psutil.swap_memory()

        if self._can_collect_stat(probe_total):
            self._collect_total_swap_space(psutil_stats, probe_total, swap_info)

        if self._can_collect_stat(probe_free):
            self._collect_free_swap_space(psutil_stats, probe_free, swap_info)