davka
davka

Reputation: 14702

how to find disk space in Python 2.7 (NOT with os.statvfs)

So, os.statvfs() is deprecated since 2.6, shutil.disk_usage() is not there yet (available in 3). What's left?
EDIT: I don't want to add a new lib at this point so psutil is also out.

I am going to run df in a subprocess and parse the output, is there a better way?

Upvotes: 1

Views: 3510

Answers (3)

Lie Ryan
Lie Ryan

Reputation: 64943

df is primarily intended for human consumption and only sometimes for scripting in shell script. The output of user space commands can sometimes be hard to parse as they're primarily intended for human consumption, though you can pass some arguments to some user space commands to have machine-parseable output. When using languages like Python, os supports most of the commonly used system features, but you can also use high level wrappers like psutil library. I highly recommend psutil if you're doing this often.

If you don't want to bring in third party libraries, I'd recommend using the /sys/class/block special filesystem (or /sys/block if you want to support legacy systems as well), alternatively you can parse /proc/partitions. The /sys, /dev, and /proc special filesystems are stable kernel interfaces designed for use in scripting, you interact with these special files by reading/writing to these special files, most of the interfaces the there are fairly easy to parse as they're designed to be used in shell scripts.

Upvotes: 2

Sheece Gardazi
Sheece Gardazi

Reputation: 567

I tested it using Anaconda2-5.3.1-Windows-x86_64, psutil came installed:

import psutil

obj_Disk = psutil.disk_usage('/')

print (obj_Disk.total / (1024.0 ** 3),"GB")
print (obj_Disk.used / (1024.0 ** 3),"GB")
print (obj_Disk.free / (1024.0 ** 3),"GB")
print (obj_Disk.percent)

Reference:

https://pypi.python.org/pypi/psutil

Get hard disk size in Python

Upvotes: 6

Eduardo Scartezini
Eduardo Scartezini

Reputation: 31

  1. os.system('df -k /')
  2. psutil.disk_usage('/')

Upvotes: 2

Related Questions