3
\$\begingroup\$

The hard drive in my dev box is running out of space so I wrote this little script to try and free up space until I get a new drive.

My Concerns

  1. Is the code pythonic?
  2. Does the code go against any best practices?

import glob
import os
import psutil
import shutil

PATHS = ['/var/log/*', '/tmp/*', '/home/ricky/Downloads/']

USAGE = psutil.disk_usage('/').percent

if os.geteuid() != 0:
    exit("You need to have root privileges to run this script.")

def flatten(alist):
    if alist == []:
        return []
    elif type(alist) is not list:
        return [alist]
    else:
        return flatten(alist[0]) + flatten(alist[1:])

if __name__ == '__main__':
    for path in flatten(map(glob.glob, PATHS)):
        if os.path.isfile(path):
            os.remove(path)
        if os.path.isdir(path):
            shutil.rmtree(path)

    print "Usage Before {}\nUsage After {}".format(USAGE, psutil.disk_usage('/').percent)

Example Output:

ricky@ricky-OptiPlex-330:~/Projects/Python 
$ sudo python cleanup.py 
Usage Before 83.5
Usage After 82.1
\$\endgroup\$
  • 4
    \$\begingroup\$ Why not just do sudo rm -rf /var/log/* /tmp/*? \$\endgroup\$ – 200_success Aug 27 '17 at 22:44
  • \$\begingroup\$ codereview.stackexchange.com/users/9357/200-success This will work on Windows Mac and Linux \$\endgroup\$ – Ricky Wilson Aug 27 '17 at 22:51
  • 2
    \$\begingroup\$ Windows has rd /s /q. \$\endgroup\$ – 200_success Aug 27 '17 at 22:54
  • \$\begingroup\$ Note that your code will quite possibly break some daemons and logging. This is bad code not in terms of style but in terms of how it does what it does. \$\endgroup\$ – Gnudiff Aug 29 '17 at 12:34
  • \$\begingroup\$ /tmp directory sometimes contains files that are USED by system as it runs. Logging function of some daemons will break if you just remove the files they write to. Logfile sizes are controlled using rotate logs and similar daemons. /tmp directory is usually emptied by system as you reboot. \$\endgroup\$ – Gnudiff Aug 29 '17 at 12:39
3
\$\begingroup\$
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.