0

I want to create an intelligent DiscFree indicator.

Code:

import os
os.system("df -h") 

I want to use regular expression (to cut the size in MB), but I can't, because the function returns disk space and value "0".

result = os.system("df -h")

Variable "result" is "0".

How can I access to disk space and use it?

  • 1
    Use `subprocess`, in particular [`subprocess.check_output`](https://docs.python.org/3/library/subprocess.html#subprocess.check_output). –  Jun 20 '14 at 09:10
  • 1
    possible duplicate of [Retrieving the output of subprocess.call()](http://stackoverflow.com/questions/1996518/retrieving-the-output-of-subprocess-call) – vaultah Jun 20 '14 at 09:11
  • The `0` you are seeing is the return code of the successfull `df -h` call. – Jasper Jun 20 '14 at 12:15

3 Answers3

1

Use subprocess for invoking console commands:

import subprocess

def command(cmd):
    try:
        p = subprocess.Popen(cmd, shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, close_fds = True)
        stdout = p.communicate()
        return stdout[0]
    except Exception as ex:
        raise Exception(ex)

df = command("df -h")

print(df)

Which prints:

Filesystem      Size   Used  Avail Capacity  iused    ifree %iused  Mounted on
/dev/disk0s2   233Gi  160Gi   72Gi    69% 42083619 18985821   69%   /
devfs          187Ki  187Ki    0Bi   100%      648        0  100%   /dev
map -hosts       0Bi    0Bi    0Bi   100%        0        0  100%   /net
map auto_home    0Bi    0Bi    0Bi   100%        0        0  100%   /home
jabaldonedo
  • 25,822
  • 8
  • 77
  • 77
0

use os.popen instead of os.system

import os
result = os.popen("df -h").read()
print result

Note: os.popen is deprecated as of Python 2.6 and subprocess is available since python 2.4 so if you want code to work on Python >= 2.6 use subprocess and if support for Python < 2.4 is important use os.popen.

codefreak
  • 6,950
  • 3
  • 42
  • 51
0

As an alternative, you can consider using some library functions to get the free space:

import os
s = os.statvfs('/')
print (s.f_bavail * s.f_frsize) / 1024**2
perreal
  • 94,503
  • 21
  • 155
  • 181