Cross platform way to list disk drives on Linux, Windows and Mac using Python?

佐手、 提交于 2019-12-18 20:18:06

问题


I am using Python2.6. I am trying to list the disk drives that a system may have.

On Windows, it may be something like C:/, D:/, E:/, etc. On Linux, it may be something like /boot, /media/SDCard, etc. And I don't know what it's like on a Mac. Maybe something under /Volumes.

Does anyone know of a cross platform way (that is, one which works on Linux, Windows and Mac) in Python?

Thanks!


回答1:


There isn't really a unified naming scheme for Linux devices that guarantees you a formatable block device. There are conventions, but they can vary widely and I can call my thumb-drive /Thomas/O if I want and there is no cross-platform way in Python to know:

  1. That /Thomas/O corresponds to /dev/sdf1
  2. That /dev/sdf1 can have a FAT32 filesystem made on it
  3. That /dev/sdf is not preferred to /dev/sdf1

I'm pretty sure that neither is there a cross-platform Python module which will allow you to determine that H:/ is formattable on a Windows system but that Z:/ is not.

Each system will require its own specific checks and validations which you could best learn from studying open-source disk manipulation software.




回答2:


The psutil package (https://pypi.python.org/pypi/psutil) has a disk_partitions function.

Windows:

>>> import psutil
>>> psutil.disk_partitions()
[sdiskpart(device='C:\\', mountpoint='C:\\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='D:\\', mountpoint='D:\\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='E:\\', mountpoint='E:\\', fstype='', opts='cdrom'), sdiskpart(device='F:\\', mountpoint='F:\\', fstype='NTFS', opts='rw,fixed')]

Linux:

>>> import psutil
>>> psutil.disk_partitions()
[sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,errors=remount-ro'), sdiskpart(device='/dev/sr0', mountpoint='/media/VBOXADDITIONS_4.3.10_93012', fstype='iso9660', opts='ro,nosuid,nodev,uid=1000,gid=1000,iocharset=utf8,mode=0400,dmode=0500,uhelper=udisks')]



回答3:


Eric Smith's answer to use psutil works well for me on Windows, but on OS X, I prefer this:

from os import listdir
listdir('/Volumes')

It gives you back the human readable names that, at least in my case, would be preferable (IE, it gives you Macintosh HD instead of / or /dev/disk0s2.)




回答4:


I don't see a way in psutil to include net mounts on Windows. I.e., \foobar\home is mapped to X:, but X: does not appear in the list returned by psutil.disk_partitions() (local drives are).



来源:https://stackoverflow.com/questions/3596485/cross-platform-way-to-list-disk-drives-on-linux-windows-and-mac-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!