Method One:
Use Commands.getoutput to invoke the shell command df to get disk usage:
Import commands>>> Import commands>>> disk_use=commands.getoutput (' df-h ') >>> disk_use ' Filesystem Size used Avail use% mounted on\n/dev/sda2 18G 5.7G 12G 34%/\ntmpfs 931M 0 931 M 0%/dev/shm ' >>> print disk_use.split (' \ n ') [1].split () [4]34%
The command returns the result of the DF command execution and then processes the result to get the percentage of usage
Method Two (feeling a bit troublesome and not quite clear):
On the Internet, you can use the OS.STATVFS function to process (return the file system containing file descriptor FD files, which is valid in Unix):
>>> Os.statvfs ('/') Posix.statvfs_result (f_bsize=4096, f_frsize=4096, f_blocks=4656351, f_bfree=3172146, f_ bavail=2935615, f_files=1183200, f_ffree=1105800, f_favail=1105800, f_flag=4096, f_namemax=255)
Return result Description:
Statvfs. F_bsizepreferred file system block size.statvfs.F_FRSIZEFundamental file system block Size.statvfs.F_BLOCKSTotal number of blocks in the filesystem.statvfs.F_BFREETotal number of free Blocks.statvfs.F_BAVAILFree blocks available to Non-super User.statvfs.F_FILESTotal number of file nodes.statvfs.F_FFREETotal number of free file Nodes.statvfs.F_FAVAILFree nodes Available to Non-super User.statvfs.F_FLAGFlags. System Dependent:see Statvfs () man page.statvfs.F_NAMEMAXMaximum file name length.
Code:
>>> Import os>>> Os.statvfs ('/') Posix.statvfs_result (f_bsize=4096, f_frsize=4096, f_blocks= 4656351, f_bfree=3172146, f_bavail=2935615, f_files=1183200, f_ffree=1105800, f_favail=1105800, f_flag=4096, f_ namemax=255) >>> Vfs=os.statvfs ('/') >>> print '%d%% '% int ((vfs.f_blocks-vfs.f_bfree)/float (vfs.f_ Blocks) *100) 31%
Method Three:
Use the Os.popen () function to get the result of the shell command execution:
>>> os.popen (' df-h '). Read () ' Filesystem Size used Avail use% mounted on\n/dev/sda2 18G 5.7G 12G 34%/\ntmpfs 931M 0 931M 0%/dev/shm\n '
I wanted to use Os.system to execute the DF command to get the result, but after execution it was found that the command returned a exit_status.
>>> os.system (' df-h ') Filesystem Size used Avail use% mounted on/dev/sda2 18G 5.7G 12G 34%/tmpf S 931M 0 931M 0%/dev/shm0
The last side of a 0 is the return value of this function, and the return value is an int type. When the result is converted to a list, there is only one element ' 0 ':
>>> list (str (Os.system (' Df-h))) Filesystem Size used Avail use% mounted on/dev/sda2 18G 5.7G 12G 34%/tmpfs 931M 0 931M 0%/dev/shm[' 0 ']
So you can only use OS.STATVFS and commands.getouput to get disk usage, but don't know why the two results are different. I appreciate it if someone sees me pointing out a mistake.
Python notes-disk usage