Python psutil.disk_partitions() Examples

The following are 30 code examples of psutil.disk_partitions(). 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: investigator.py    From cpu-g with GNU General Public License v3.0 6 votes vote down vote up
def disksinfo(self):
        values = []
        disk_partitions = psutil.disk_partitions(all=False)
        for partition in disk_partitions:
            usage = psutil.disk_usage(partition.mountpoint)
            device = {'device': partition.device,
                      'mountpoint': partition.mountpoint,
                      'fstype': partition.fstype,
                      'opts': partition.opts,
                      'total': usage.total,
                      'used': usage.used,
                      'free': usage.free,
                      'percent': usage.percent
                      }
            values.append(device)
        values = sorted(values, key=lambda device: device['device'])
        return values 
Example #3
Source File: OP_1_Connection.py    From OP_Manager with MIT License 6 votes vote down vote up
def getMountPath(device):
    """
    Checks if the partition is mounted if not it return ""
    :param device: Target device being string "OP1" or "OPZ"
    :return: "" is not found
    """
    mountpath = getmountpath(device)
    # mountPoint = ""
    for i, disk in enumerate(disk_partitions()):
        print(disk)
        if disk.device == mountpath:
            mountPoint = disk.mountpoint
            if device == "OP1":
                config["OP_1_Mounted_Dir"] = mountPoint
                print(config["OP_1_Mounted_Dir"])
            elif device == "OPZ":
                config["OP_Z_Mounted_Dir"] = mountPoint
                print(config["OP_Z_Mounted_Dir"])
            return mountPoint
    return "" 
Example #4
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 #5
Source File: system_status.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def getStatus(self, max_age=0.8):
        """
        Get current system status.

        max_age: maximum tolerable age of cached status information.  Set to
        None to force a refresh regardless of cache age.

        Returns a dictionary with fields 'cpu_load', 'mem', 'disk', and
        'network'.
        """
        timestamp = time.time()
        if (max_age is None or timestamp > self.timestamp + max_age):
            self.timestamp = timestamp
            self.refreshCpuLoad()
            self.refreshMemoryInfo()
            self.refreshDiskInfo()
            self.refreshNetworkTraffic()

        result = {
            'cpu_load': self.cpu_load,
            'mem': self.mem,
            'disk': self.disk_partitions,
            'network': self.network
        }
        return result 
Example #6
Source File: umount.py    From restatic with GNU General Public License v3.0 6 votes vote down vote up
def prepare(cls, profile):
        ret = super().prepare(profile)
        if not ret["ok"]:
            return ret
        else:
            ret["ok"] = False  # Set back to false, so we can do our own checks here.

        ret["active_mount_points"] = []
        partitions = psutil.disk_partitions(all=True)
        for p in partitions:
            if p.device == "resticfs":
                ret["active_mount_points"].append(p.mountpoint)

        if len(ret["active_mount_points"]) == 0:
            ret["message"] = "No active Restic mounts found."
            return ret

        cmd = ["restic", "umount", "--log-json"]

        ret["ok"] = True
        ret["cmd"] = cmd

        return ret 
Example #7
Source File: disk_utils.py    From agentless-system-crawler with Apache License 2.0 6 votes vote down vote up
def crawl_disk_partitions():
    partitions = []
    for partition in psutil.disk_partitions(all=True):
        try:
            pdiskusage = psutil.disk_usage(partition.mountpoint)
            partitions.append((partition.mountpoint, DiskFeature(
                partition.device,
                100.0 - pdiskusage.percent,
                partition.fstype,
                partition.mountpoint,
                partition.opts,
                pdiskusage.total,
            ), 'disk'))
        except OSError:
            continue
    return partitions 
Example #8
Source File: test_linux.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_disk_partitions_and_usage(self):
        # test psutil.disk_usage() and psutil.disk_partitions()
        # against "df -a"
        def df(path):
            out = sh('df -P -B 1 "%s"' % path).strip()
            lines = out.split('\n')
            lines.pop(0)
            line = lines.pop(0)
            dev, total, used, free = line.split()[:4]
            if dev == 'none':
                dev = ''
            total, used, free = int(total), int(used), int(free)
            return dev, total, used, free

        for part in psutil.disk_partitions(all=False):
            usage = psutil.disk_usage(part.mountpoint)
            dev, total, used, free = df(part.mountpoint)
            self.assertEqual(usage.total, total)
            # 10 MB tollerance
            if abs(usage.free - free) > 10 * 1024 * 1024:
                self.fail("psutil=%s, df=%s" % (usage.free, free))
            if abs(usage.used - used) > 10 * 1024 * 1024:
                self.fail("psutil=%s, df=%s" % (usage.used, used)) 
Example #9
Source File: test_linux.py    From vnpy_crypto with MIT License 6 votes vote down vote up
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) 
Example #10
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 #11
Source File: test_linux.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_against_df(self):
        # test psutil.disk_usage() and psutil.disk_partitions()
        # against "df -a"
        def df(path):
            out = sh('df -P -B 1 "%s"' % path).strip()
            lines = out.split('\n')
            lines.pop(0)
            line = lines.pop(0)
            dev, total, used, free = line.split()[:4]
            if dev == 'none':
                dev = ''
            total, used, free = int(total), int(used), int(free)
            return dev, total, used, free

        for part in psutil.disk_partitions(all=False):
            usage = psutil.disk_usage(part.mountpoint)
            dev, total, used, free = df(part.mountpoint)
            self.assertEqual(usage.total, total)
            self.assertAlmostEqual(usage.free, free,
                                   delta=TOLERANCE_DISK_USAGE)
            self.assertAlmostEqual(usage.used, used,
                                   delta=TOLERANCE_DISK_USAGE) 
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_procfs_path(self):
        tdir = self.get_testfn()
        os.mkdir(tdir)
        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" 
Example #13
Source File: script.py    From heartbeats with MIT License 6 votes vote down vote up
def get_disk_info():
    disk_info = []
    for part in psutil.disk_partitions(all=False):
        if os.name == 'nt':
            if 'cdrom' in part.opts or part.fstype == '':
                # skip cd-rom drives with no disk in it; they may raise
                # ENOENT, pop-up a Windows GUI error for a non-ready
                # partition or just hang.
                continue
        usage = psutil.disk_usage(part.mountpoint)
        disk_info.append({
            'device':  part.device,
            'total':  usage.total,
            'used': usage.used,
            'free': usage.free,
            'percent': usage.percent,
            'fstype': part.fstype,
            'mountpoint': part.mountpoint
        })
    return disk_info 
Example #14
Source File: system_status.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        self.timestamp = time.time()
        self.cpu_load = []
        self.mem = dict(total = 0,
                        available = 0,
                        free = 0,
                        cached = 0,
                        buffers = 0)
        self.disk_partitions = {}
        self.network = {}

        partitions = psutil.disk_partitions()
        for p in partitions:
            if p.mountpoint in self.INCLUDED_PARTITIONS:
                usage = psutil.disk_usage(p.mountpoint)
                self.disk_partitions[p.mountpoint] = {
                    'total': usage.total,
                    'used': usage.used
                } 
Example #15
Source File: local.py    From quay with Apache License 2.0 6 votes vote down vote up
def validate(self, client):
        super(LocalStorage, self).validate(client)

        # Load the set of disk mounts.
        try:
            mounts = psutil.disk_partitions(all=True)
        except:
            logger.exception("Could not load disk partitions")
            return

        # Verify that the storage's root path is under a mounted Docker volume.
        for mount in mounts:
            if mount.mountpoint != "/" and self._root_path.startswith(mount.mountpoint):
                return

        raise Exception(
            "Storage path %s is not under a mounted volume.\n\n"
            "Registry data must be stored under a mounted volume "
            "to prevent data loss" % self._root_path
        ) 
Example #16
Source File: simple_monitor.py    From You-are-Pythonista with GNU General Public License v3.0 6 votes vote down vote up
def log_generate():
    '''
    生成日志格式
    '''
    # 获取cpu百分比
    cpu_percent = psutil.cpu_percent()
    # 查看系统内存
    mem = psutil.virtual_memory()
    # 计算内存占用百分比
    mem_percent = int(mem.used / mem.total * 100)
    # 获取系统分区信息
    disk_partition = psutil.disk_partitions()
    # 计算系统磁盘占用百分比
    disk_percent = {mount_point : '{} %'.format(psutil.disk_usage('{}'.format(mount_point))[3]) \
                    for mount_point in ( dp.mountpoint for dp in disk_partition )}

    return {get_ip_address():{'cpu': '{} %'.format(cpu_percent), \
                              'mem': '{} %'.format(mem_percent), \
                              'disk':disk_percent, \
                              'time':int(time.time())}} 
Example #17
Source File: windows_system_metrics.py    From scalyr-agent-2 with Apache License 2.0 6 votes vote down vote up
def partion_disk_usage(sub_metric):
    mountpoints_initialized = [0]
    mountpoints = []

    def gather_metric():
        if mountpoints_initialized[0] == 0:
            for p in psutil.disk_partitions():
                # Only add to list of mountpoints if fstype is
                # specified.  This prevents reading from empty drives
                # such as cd-roms, card readers etc.
                if p.fstype:
                    mountpoints.append(p.mountpoint)
            mountpoints_initialized[0] = 1

        for mountpoint in mountpoints:
            try:
                diskusage = psutil.disk_usage(mountpoint)
                yield getattr(diskusage, sub_metric), {"partition": mountpoint}
            except OSError:
                # Certain partitions, like a CD/DVD drive, are expected to fail
                pass

    gather_metric.__doc__ = "TODO"
    return gather_metric 
Example #18
Source File: hard_drives.py    From node-launcher with MIT License 6 votes vote down vote up
def list_partitions(self) -> List[Partition]:
        partitions = []
        try:
            ps = psutil.disk_partitions()
        except:
            log.warning(
                'list_partitions',
                exc_info=True
            )
            return partitions
        partition_paths = [p.mountpoint for p in ps if 'removable' not in p.opts]
        log.info(
            'partition_paths',
            partition_paths=partition_paths
        )
        for path in partition_paths:
            free_gb = self.get_gb(path)
            partitions.append(Partition(path, free_gb), )
        return partitions 
Example #19
Source File: umount.py    From vorta with GNU General Public License v3.0 6 votes vote down vote up
def prepare(cls, profile):
        ret = super().prepare(profile)
        if not ret['ok']:
            return ret
        else:
            ret['ok'] = False  # Set back to false, so we can do our own checks here.

        ret['active_mount_points'] = []
        partitions = psutil.disk_partitions(all=True)
        for p in partitions:
            if p.device == 'borgfs':
                ret['active_mount_points'].append(os.path.normpath(p.mountpoint))

        if len(ret['active_mount_points']) == 0:
            ret['message'] = trans_late('messages', 'No active Borg mounts found.')
            return ret

        cmd = ['borg', 'umount', '--log-json']

        ret['ok'] = True
        ret['cmd'] = cmd

        return ret 
Example #20
Source File: disk_status.py    From marsnake with GNU General Public License v3.0 6 votes vote down vote up
def disk_status(response):
    #name    STATS   USED    MOUNT   FILESYSTEM
    for item in psutil.disk_partitions():
        device, mountpoint, fstype, opts = item
        
        try:
            total, used, free, percent = psutil.disk_usage(mountpoint)
            
            response["disk"][device] = {
                "fstype" : fstype,
                "total" : common.size_human_readable(total),
                "percent" : percent,
                "mountpoint" : mountpoint,
                "opts" : opts
            }
        except Exception:
            pass 
Example #21
Source File: _blockdevice.py    From flocker with Apache License 2.0 6 votes vote down vote up
def umount_all(root_path):
    """
    Unmount all devices with mount points contained in ``root_path``.

    :param FilePath root_path: A directory in which to search for mount points.
    """
    def is_under_root(path):
        try:
            FilePath(path).segmentsFrom(root_path)
        except ValueError:
            return False
        return True

    partitions_under_root = list(p for p in psutil.disk_partitions()
                                 if is_under_root(p.mountpoint))
    for partition in partitions_under_root:
        umount(FilePath(partition.mountpoint)) 
Example #22
Source File: script_ex.py    From heartbeats with MIT License 6 votes vote down vote up
def get_disk_info():
    disk_info = []
    for part in psutil.disk_partitions(all=False):
        if os.name == 'nt':
            if 'cdrom' in part.opts or part.fstype == '':
                # skip cd-rom drives with no disk in it; they may raise
                # ENOENT, pop-up a Windows GUI error for a non-ready
                # partition or just hang.
                continue
        usage = psutil.disk_usage(part.mountpoint)
        disk_info.append({
            'device':  part.device,
            'total':  usage.total,
            'used': usage.used,
            'free': usage.free,
            'percent': usage.percent,
            'fstype': part.fstype,
            'mountpoint': part.mountpoint
        })
    return disk_info 
Example #23
Source File: disk_usage.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    templ = "%-17s %8s %8s %8s %5s%% %9s  %s"
    print(templ % ("Device", "Total", "Used", "Free", "Use ", "Type",
                   "Mount"))
    for part in psutil.disk_partitions(all=False):
        if os.name == 'nt':
            if 'cdrom' in part.opts or part.fstype == '':
                # skip cd-rom drives with no disk in it; they may raise
                # ENOENT, pop-up a Windows GUI error for a non-ready
                # partition or just hang.
                continue
        usage = psutil.disk_usage(part.mountpoint)
        print(templ % (
            part.device,
            bytes2human(usage.total),
            bytes2human(usage.used),
            bytes2human(usage.free),
            int(usage.percent),
            part.fstype,
            part.mountpoint)) 
Example #24
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def partitions():
                return psutil.disk_partitions() 
Example #25
Source File: system_status.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def refreshDiskInfo(self):
        for key, value in six.iteritems(self.disk_partitions):
            usage = psutil.disk_usage(key)
            self.disk_partitions[key]['total'] = usage.total
            self.disk_partitions[key]['used'] = usage.used 
Example #26
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def partitions():
                return psutil.disk_partitions() 
Example #27
Source File: __init__.py    From platypush with MIT License 5 votes vote down vote up
def disk_usage(self, path: Optional[str] = None) -> Union[DiskUsageResponse, DiskResponseList]:
        """
        Get the usage of a mounted disk.

        :param path: Path where the device is mounted (default: get stats for all mounted devices).
        :return: :class:`platypush.message.response.system.DiskUsageResponse` or list of
            :class:`platypush.message.response.system.DiskUsageResponse`.
        """
        import psutil

        if path:
            usage = psutil.disk_usage(path)
            return DiskUsageResponse(
                 path=path,
                 total=usage.total,
                 used=usage.used,
                 free=usage.free,
                 percent=usage.percent,
            )
        else:
            disks = {p.mountpoint: psutil.disk_usage(p.mountpoint)
                     for p in psutil.disk_partitions()}

            return DiskResponseList([
                DiskUsageResponse(
                    path=path,
                    total=disk.total,
                    used=disk.used,
                    free=disk.free,
                    percent=disk.percent,
                ) for path, disk in disks.items()
            ]) 
Example #28
Source File: __init__.py    From platypush with MIT License 5 votes vote down vote up
def disk_partitions(self) -> DiskResponseList:
        """
        Get the list of partitions mounted on the system.
        :return: list of :class:`platypush.message.response.system.DiskPartitionResponse`
        """
        import psutil
        parts = psutil.disk_partitions()
        return DiskResponseList([
            DiskPartitionResponse(
                device=p.device,
                mount_point=p.mountpoint,
                fstype=p.fstype,
                opts=p.opts,
            ) for p in parts
        ]) 
Example #29
Source File: overview_mac.py    From marsnake with GNU General Public License v3.0 5 votes vote down vote up
def get_mem_disk_info(response):
	#name	STATS   USED	MOUNT   FILESYSTEM
	for item in psutil.disk_partitions():
		device, mountpoint, fstype, opts = item

		try:
			total, used, free, percent = psutil.disk_usage(mountpoint)

			response["disk"][device] = percent
		except Exception:
			pass

	mem = psutil.virtual_memory()
	response["ram"]["total"] = common.size_human_readable(mem[0])
	response["ram"]["used"] = common.size_human_readable(mem[3]) 
Example #30
Source File: usb_detect_linux.py    From marsnake with GNU General Public License v3.0 5 votes vote down vote up
def do(self):
		#(u'add', u'/dev/sdb', u'disk', u'')
		#(u'add', u'/dev/sdb1', u'partition', u'ntfs')
		for device in iter(self.monitor.poll, None):
			if 'ID_FS_TYPE' in device:
				mnt = None
				
				for item in psutil.disk_partitions():
					dev, mountpoint, fstype, opts = item
					
					if dev == device.device_node:
						mnt = mountpoint
						break
						
				if device.action == "add":
					self.usb_plugged({
						"node" : device.device_node,
						"type" : device.device_type,
						"fs_type" : device.get('ID_FS_TYPE'),
						"mnt" : mnt
					})
				elif device.action == "remove":
					self.usb_unplugged({
						"node" : device.device_node,
						"type" : device.device_type,
						"fs_type" : device.get('ID_FS_TYPE'),
						"mnt" : mnt
					})