I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I’m currently parsing the output of the various system calls (df, dir) to accomplish this — is there a better way?
asked Sep 9, 2008 at 11:36
1
import ctypes
import os
import platform
import sys
def get_free_space_mb(dirname):
"""Return folder/drive free space (in megabytes)."""
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))
return free_bytes.value / 1024 / 1024
else:
st = os.statvfs(dirname)
return st.f_bavail * st.f_frsize / 1024 / 1024
Note that you must pass a directory name for GetDiskFreeSpaceEx()
to work
(statvfs()
works on both files and directories). You can get a directory name
from a file with os.path.dirname()
.
Also see the documentation for os.statvfs()
and GetDiskFreeSpaceEx
.
answered Mar 3, 2010 at 14:45
7
Install psutil using pip install psutil
. Then you can get the amount of free space in bytes using:
import psutil
print(psutil.disk_usage(".").free)
smci
31.4k18 gold badges112 silver badges146 bronze badges
answered Apr 29, 2015 at 12:43
jhassejhasse
2,3021 gold badge30 silver badges40 bronze badges
3
You could use the wmi module for windows and os.statvfs for unix
for window
import wmi
c = wmi.WMI ()
for d in c.Win32_LogicalDisk():
print( d.Caption, d.FreeSpace, d.Size, d.DriveType)
for unix or linux
from os import statvfs
statvfs(path)
answered Oct 12, 2013 at 9:20
ErxinErxin
1,7514 gold badges19 silver badges33 bronze badges
6
If you’re running python3:
Using shutil.disk_usage()
with os.path.realpath('/')
name-regularization works:
from os import path
from shutil import disk_usage
print([i / 1000000 for i in disk_usage(path.realpath('/'))])
Or
total_bytes, used_bytes, free_bytes = disk_usage(path.realpath('D:\Users\phannypack'))
print(total_bytes / 1000000) # for Mb
print(used_bytes / 1000000)
print(free_bytes / 1000000)
giving you the total, used, & free space in MB.
answered Feb 1, 2018 at 4:52
Rob TruxalRob Truxal
5,5883 gold badges20 silver badges39 bronze badges
2
If you dont like to add another dependency you can for windows use ctypes to call the win32 function call directly.
import ctypes
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(u'c:\'), None, None, ctypes.pointer(free_bytes))
if free_bytes.value == 0:
print 'dont panic'
answered Nov 13, 2009 at 9:22
1
From Python 3.3 you can use shutil.disk_usage(«/»).free from standard library for both Windows and UNIX
answered Aug 11, 2016 at 7:11
MišoMišo
2,0091 gold badge25 silver badges24 bronze badges
You can use df as a cross-platform way. It is a part of GNU core utilities. These are the core utilities which are expected to exist on every operating system. However, they are not installed on Windows by default (Here, GetGnuWin32 comes in handy).
df is a command-line utility, therefore a wrapper required for scripting purposes.
For example:
from subprocess import PIPE, Popen
def free_volume(filename):
"""Find amount of disk space available to the current user (in bytes)
on the file system containing filename."""
stats = Popen(["df", "-Pk", filename], stdout=PIPE).communicate()[0]
return int(stats.splitlines()[1].split()[3]) * 1024
answered Sep 9, 2008 at 23:48
jfsjfs
390k188 gold badges965 silver badges1647 bronze badges
2
Below code returns correct value on windows
import win32file
def get_free_space(dirname):
secsPerClus, bytesPerSec, nFreeClus, totClus = win32file.GetDiskFreeSpace(dirname)
return secsPerClus * bytesPerSec * nFreeClus
answered Mar 8, 2016 at 6:53
Sanjay BhosaleSanjay Bhosale
6852 gold badges8 silver badges18 bronze badges
The os.statvfs() function is a better way to get that information for Unix-like platforms (including OS X). The Python documentation says «Availability: Unix» but it’s worth checking whether it works on Windows too in your build of Python (ie. the docs might not be up to date).
Otherwise, you can use the pywin32 library to directly call the GetDiskFreeSpaceEx function.
answered Sep 9, 2008 at 11:40
Greg HewgillGreg Hewgill
927k180 gold badges1136 silver badges1275 bronze badges
1
I Don’t know of any cross-platform way to achieve this, but maybe a good workaround for you would be to write a wrapper class that checks the operating system and uses the best method for each.
For Windows, there’s the GetDiskFreeSpaceEx method in the win32 extensions.
answered Sep 9, 2008 at 11:47
hasseghasseg
6,76736 silver badges41 bronze badges
Most previous answers are correct, I’m using Python 3.10 and shutil.
My use case was Windows and C drive only ( but you should be able to extend this for you Linux and Mac as well (here is the documentation)
Here is the example for Windows:
import shutil
total, used, free = shutil.disk_usage("C:/")
print("Total: %d GiB" % (total // (2**30)))
print("Used: %d GiB" % (used // (2**30)))
print("Free: %d GiB" % (free // (2**30)))
answered Jul 25, 2022 at 20:32
grepitgrepit
20.3k6 gold badges100 silver badges81 bronze badges
I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I’m currently parsing the output of the various system calls (df, dir) to accomplish this — is there a better way?
asked Sep 9, 2008 at 11:36
1
import ctypes
import os
import platform
import sys
def get_free_space_mb(dirname):
"""Return folder/drive free space (in megabytes)."""
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))
return free_bytes.value / 1024 / 1024
else:
st = os.statvfs(dirname)
return st.f_bavail * st.f_frsize / 1024 / 1024
Note that you must pass a directory name for GetDiskFreeSpaceEx()
to work
(statvfs()
works on both files and directories). You can get a directory name
from a file with os.path.dirname()
.
Also see the documentation for os.statvfs()
and GetDiskFreeSpaceEx
.
answered Mar 3, 2010 at 14:45
7
Install psutil using pip install psutil
. Then you can get the amount of free space in bytes using:
import psutil
print(psutil.disk_usage(".").free)
smci
31.4k18 gold badges112 silver badges146 bronze badges
answered Apr 29, 2015 at 12:43
jhassejhasse
2,3021 gold badge30 silver badges40 bronze badges
3
You could use the wmi module for windows and os.statvfs for unix
for window
import wmi
c = wmi.WMI ()
for d in c.Win32_LogicalDisk():
print( d.Caption, d.FreeSpace, d.Size, d.DriveType)
for unix or linux
from os import statvfs
statvfs(path)
answered Oct 12, 2013 at 9:20
ErxinErxin
1,7514 gold badges19 silver badges33 bronze badges
6
If you’re running python3:
Using shutil.disk_usage()
with os.path.realpath('/')
name-regularization works:
from os import path
from shutil import disk_usage
print([i / 1000000 for i in disk_usage(path.realpath('/'))])
Or
total_bytes, used_bytes, free_bytes = disk_usage(path.realpath('D:\Users\phannypack'))
print(total_bytes / 1000000) # for Mb
print(used_bytes / 1000000)
print(free_bytes / 1000000)
giving you the total, used, & free space in MB.
answered Feb 1, 2018 at 4:52
Rob TruxalRob Truxal
5,5883 gold badges20 silver badges39 bronze badges
2
If you dont like to add another dependency you can for windows use ctypes to call the win32 function call directly.
import ctypes
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(u'c:\'), None, None, ctypes.pointer(free_bytes))
if free_bytes.value == 0:
print 'dont panic'
answered Nov 13, 2009 at 9:22
1
From Python 3.3 you can use shutil.disk_usage(«/»).free from standard library for both Windows and UNIX
answered Aug 11, 2016 at 7:11
MišoMišo
2,0091 gold badge25 silver badges24 bronze badges
You can use df as a cross-platform way. It is a part of GNU core utilities. These are the core utilities which are expected to exist on every operating system. However, they are not installed on Windows by default (Here, GetGnuWin32 comes in handy).
df is a command-line utility, therefore a wrapper required for scripting purposes.
For example:
from subprocess import PIPE, Popen
def free_volume(filename):
"""Find amount of disk space available to the current user (in bytes)
on the file system containing filename."""
stats = Popen(["df", "-Pk", filename], stdout=PIPE).communicate()[0]
return int(stats.splitlines()[1].split()[3]) * 1024
answered Sep 9, 2008 at 23:48
jfsjfs
390k188 gold badges965 silver badges1647 bronze badges
2
Below code returns correct value on windows
import win32file
def get_free_space(dirname):
secsPerClus, bytesPerSec, nFreeClus, totClus = win32file.GetDiskFreeSpace(dirname)
return secsPerClus * bytesPerSec * nFreeClus
answered Mar 8, 2016 at 6:53
Sanjay BhosaleSanjay Bhosale
6852 gold badges8 silver badges18 bronze badges
The os.statvfs() function is a better way to get that information for Unix-like platforms (including OS X). The Python documentation says «Availability: Unix» but it’s worth checking whether it works on Windows too in your build of Python (ie. the docs might not be up to date).
Otherwise, you can use the pywin32 library to directly call the GetDiskFreeSpaceEx function.
answered Sep 9, 2008 at 11:40
Greg HewgillGreg Hewgill
927k180 gold badges1136 silver badges1275 bronze badges
1
I Don’t know of any cross-platform way to achieve this, but maybe a good workaround for you would be to write a wrapper class that checks the operating system and uses the best method for each.
For Windows, there’s the GetDiskFreeSpaceEx method in the win32 extensions.
answered Sep 9, 2008 at 11:47
hasseghasseg
6,76736 silver badges41 bronze badges
Most previous answers are correct, I’m using Python 3.10 and shutil.
My use case was Windows and C drive only ( but you should be able to extend this for you Linux and Mac as well (here is the documentation)
Here is the example for Windows:
import shutil
total, used, free = shutil.disk_usage("C:/")
print("Total: %d GiB" % (total // (2**30)))
print("Used: %d GiB" % (used // (2**30)))
print("Free: %d GiB" % (free // (2**30)))
answered Jul 25, 2022 at 20:32
grepitgrepit
20.3k6 gold badges100 silver badges81 bronze badges
Время чтение: 1 минуту
2022-04-19
Для решение такой задачи можно воспользоваться методом » disk_usage» из пакета «shutil» и определить сколько место на диске осталось, сколько занято и сколько использовано.
import shutil result = shutil.disk_usage(‘G:/’) print(result) |
Вывод — «usage(total=460863827968, used=87581265920, free=373282562048)»
Для читаемости и удобства, можно вывести информацию в Гб.
import shutil result = shutil.disk_usage(‘G:/’) gb = 10 **9 print(f«Всего места: {result.total/gb:.2f}») print(f«Места использовано: {result.used/gb:.2f}») print(f«Места осталось: {result.free/gb:.2f}») |
Вывод будет такой:
Всего места: 460.86
Места использовано: 87.58
Места осталось: 373.28
Printing out the type can help, when you don’t know how to handle a function’s result.
print type(os.statvfs('/'))
returns <type 'posix.statvfs_result'>
That means it isn’t a built in class instance like a string or int..
You can check what you can do with that instance with dir(instance)
print dir(os.statvfs('/'))
prints all of it’s the properties, functions, variables…
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', 'f_bavail', 'f_bfree', 'f_blocks',
'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize',
'f_namemax', 'n_fields', 'n_sequence_fields', 'n_unnamed_fields']
By accessing one of the variables, like os.statvfs('/').f_ffree
you can extract an integer.
Double check with print type(os.statvfs('/').f_ffree)
,
it does print <type 'int'>
.
Уведомления
- Начало
- » Python для экспертов
- » свободное место на диске
#1 Сен. 8, 2008 08:46:52
свободное место на диске
помогите определить свободное место на диске/томе с помошью python
Офлайн
- Пожаловаться
#3 Сен. 8, 2008 09:20:52
свободное место на диске
print os.path.getsize(“c:\”)
0 — показывает -(
Офлайн
- Пожаловаться
#4 Сен. 8, 2008 10:01:12
свободное место на диске
noster, http://mail.python.org/pipermail/python-list/1999-December/017580.html
# statvfs-example-1.pyimport statvfs
import osst = os.statvfs(".")
print "preferred block size", "=>", st[statvfs.F_BSIZE]
print "fundamental block size", "=>", st[statvfs.F_FRSIZE]
print "total blocks", "=>", st[statvfs.F_BLOCKS]
print "total free blocks", "=>", st[statvfs.F_BFREE]
print "available blocks", "=>", st[statvfs.F_BAVAIL]
print "total file nodes", "=>", st[statvfs.F_FILES]
print "total free nodes", "=>", st[statvfs.F_FFREE]
print "available nodes", "=>", st[statvfs.F_FAVAIL]
print "max file name length", "=>", st[statvfs.F_NAMEMAX]## sample output:
##
## preferred block size => 8192
## fundamental block size => 1024
## total blocks => 749443
## total free blocks => 110442
## available blocks => 35497
## total file nodes => 92158
## total free nodes => 68164
## available nodes => 68164
## max file name length => 255
В linux работает, в windows — не уверен. Поэтому и спрашивали про os
Отредактировано (Сен. 8, 2008 10:13:15)
Офлайн
- Пожаловаться
#5 Сен. 9, 2008 03:31:06
свободное место на диске
в доке написано, что os.statvfs — “Availability: Unix”
Для виндовса все хитрее — надо использовать pywin, тогда:
import win32api
r = win32api.GetDiskFreeSpace(r'd:')
free_space =r[0]*r[1]*r[2]
Отредактировано (Сен. 9, 2008 03:47:19)
Офлайн
- Пожаловаться
- Начало
- » Python для экспертов
- » свободное место на диске
import ctypes import os import platform import sys def get_free_space_mb(folder): """ Return folder/drive free space (in bytes) """ if platform.system() == 'Windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes)) return free_bytes.value/1024/1024/1024 else: st = os.statvfs(folder) return st.f_bavail * st.f_frsize/1024/1024 print(get_free_space_mb('C:\'),'GB')
import win32com.client as com def TotalSize(drive): """ Return the TotalSize of a shared drive [GB]""" try: fso = com.Dispatch("Scripting.FileSystemObject") drv = fso.GetDrive(drive) return drv.TotalSize/2**30 except: return 0 def FreeSpace(drive): """ Return the FreeSpace of a shared drive [GB]""" try: fso = com.Dispatch("Scripting.FileSystemObject") drv = fso.GetDrive(drive) return drv.FreeSpace/2**30 except: return 0 workstations = ['dolphins'] print ('Hard drive sizes:') for compName in workstations: drive = '\\' + compName + '\c$' print ('*************************************************n') print (compName) print ('TotalSize of %s = %f GB' % (drive, TotalSize(drive))) print ('FreeSpace on %s = %f GB' % (drive, FreeSpace(drive))) print ('*************************************************n')
Интеллектуальная рекомендация
Ползун на Python, ползающий по роману «Shuquge»
Предисловие: Коэффициент сложности этого краулера невелик.По сравнению с курсом, который я объяснил в прошлый раз, он имеет очень хорошую проверку и чрезмерный эффект, но есть несколько новых точек зн…
Настройка и работа среды UIAutomator
Конфигурация среды, представьте тестовый пакет UTAutomator 1. Войдите в Eclipse, создайте тестовый проект, например проект Android / Java. 2. Щелкните тестовый проект правой кнопкой мыши и выберите &l…
Android Data Data Device MayoutinFlator
Класс LayoutinFlator более практичен в приложении. Его можно назвать наполнением макета или пилота, что означает, что файл макета заполняется в желаемом положении. Этот XML -файл становится пред…
Вам также может понравиться
Linux compile node.js
1. Работа для подготовки компиляции Иди первымОфициальный сайт скачатьИсходный код node.js и распаковка: Затем установите инструмент, необходимый для компиляции в системе: 2. Введите папку исходного к…
IO Communication
Модель Bio Communication (синхронная модель блокировки IO) Модель связи: Обычно существует акцепторная нить для прослушивания соединения клиента. Он получил новую поток для каждого клиента после получ…
Материал из Xgu.ru
Перейти к: навигация, поиск
Содержание
- 1 Вопросы и ответы
- 1.1 Как правильно узнать имя текущего пользователя?
- 1.2 Как уникально идентифицировать анонимного пользователя?
- 1.2.1 Как определить, сколько свободного места на диске?
- 1.3 Есть какой-то хороший curses-тулкит для Python?
- 2 Дополнительная информация
- 3 Примечания
[править] Вопросы и ответы
[править] Как правильно узнать имя текущего пользователя?
def get_username(): return pwd.getpwuid( os.getuid() )[ 0 ]
Или:
def get_username(): return pwd.getpwuid( os.geteuid() )[ 0 ]
Другие способы: [1].
[править] Как уникально идентифицировать анонимного пользователя?
Идеи и предложения на ХэшКоде.
[править] Как определить, сколько свободного места на диске?
import os import platform import ctypes def get_free_space(folder): """ Return folder/drive free space (in bytes) """ if platform.system() == 'Windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes)) return free_bytes.value else: return os.statvfs('/folder').f_bavail*os.statvfs('/folder').f_bsize #к-во доступных пользователю блоков*размер блока
Источник: [2]
[править] Есть какой-то хороший curses-тулкит для Python?
Например, Urwid
[править] Дополнительная информация
[править] Примечания
|
||
---|---|---|
Реализации | Cython • Psyco • PyPy | |
Веб-фреймворки | Django • Flask • Zope | |
IDE | Pydev • NetBeans | |
Курсы | Python для сетевых инженеров | |
Другое | aalib • ctypes • gevent • mpmath • pjsua • Pandas • pyparsing • virtualenv • GMPY • IPython • Jinja2 • Python и Vim • Работа с модулями в Python • SWIG • Scapy • SciPy • Работа с датой и временем в Python • Python как shell • Web и Python • Алгоритмы, сложные структуры данных и дискретная математика в Python • Анализ кода Python • Интеграция Python с другими языками • Объекты и классы в Python • Оформление кода Python • Параллелизм и конкурентное исполнение в Python • Профайлинг в Python • Работа с базами данных в Python • Работа с операционной системой в Python • Работа с сетью в Python • Работа с текстами в Python • Работа с файлами в Python • Сравнение Python с другими языками • Тестирование в Python • Типы в Python • Элементы функционального программирования в Python • Элементы языка Python |
https://pypi.python.org/pypi/psutil
import psutil
obj_Disk = psutil.disk_usage('/')
print (obj_Disk.total / (1024.0 ** 3))
print (obj_Disk.used / (1024.0 ** 3))
print (obj_Disk.free / (1024.0 ** 3))
print (obj_Disk.percent)
For Python 2 till Python 3.3
Notice: As a few people mentioned in the comment section, this solution will work for Python 3.3 and above. For Python 2.7 it is best to use the psutil
library, which has a disk_usage
function, containing information about total, used and free disk space:
import psutil
hdd = psutil.disk_usage('/')
print ("Total: %d GiB" % hdd.total / (2**30))
print ("Used: %d GiB" % hdd.used / (2**30))
print ("Free: %d GiB" % hdd.free / (2**30))
Python 3.3 and above:
For Python 3.3 and above, you can use the shutil
module, which has a disk_usage
function, returning a named tuple with the amounts of total, used and free space in your hard drive.
You can call the function as below and get all information about your disk’s space:
import shutil
total, used, free = shutil.disk_usage("/")
print("Total: %d GiB" % (total // (2**30)))
print("Used: %d GiB" % (used // (2**30)))
print("Free: %d GiB" % (free // (2**30)))
Output:
Total: 931 GiB
Used: 29 GiB
Free: 902 GiB
The code is about right, but you’re using wrong fields, which may give you the wrong results on a different system. The correct way would be:
>>> os.system('df -k /')
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/root 14846608 3247272 10945876 23% /
>>> disk = os.statvfs('/')
>>> (disk.f_bavail * disk.f_frsize) / 1024
10945876L
Printing out the type can help, when you don’t know how to handle a function’s result.
print type(os.statvfs('/'))
returns <type 'posix.statvfs_result'>
That means it isn’t a built in class instance like a string or int..
You can check what you can do with that instance with dir(instance)
print dir(os.statvfs('/'))
prints all of it’s the properties, functions, variables…
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', 'f_bavail', 'f_bfree', 'f_blocks',
'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize',
'f_namemax', 'n_fields', 'n_sequence_fields', 'n_unnamed_fields']
By accessing one of the variables, like os.statvfs('/').f_ffree
you can extract an integer.
Double check with print type(os.statvfs('/').f_ffree)
,
it does print <type 'int'>
.