Skip to content

Instantly share code, notes, and snippets.

@lloeki
Created April 25, 2012 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lloeki/2492951 to your computer and use it in GitHub Desktop.
Save lloeki/2492951 to your computer and use it in GitHub Desktop.
list comprehensions
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import os
import sys
import re
from glob import iglob as glob
import time
from datetime import datetime, timedelta
# list of files to be checked
files_to_check = set([
'one.foo',
'two.foo',
])
# blacklisted usernames
blacklist = [
'ignore_me',
]
# path tools
path_template = '/home/%s/files'
username = lambda path: re.match(path_template % '(.*)', path).group(1)
filepath = lambda u, f: os.path.join(path_template % u, f)
# list of files, with username
dirs = [d for d in glob(path_template % '*')]
files = [(username(d), os.path.basename(f))
for d in dirs
for f in glob(os.path.join(d, '*'))
if username(d) not in blacklist]
# group files as sets, keyed by username
grouped_files = {}
for u, f in files:
grouped_files.setdefault(u, set())
grouped_files[u].add(f)
# shell return code
rc = 0
# find missing files
missing_files = [(u, f) for u, fs in grouped_files.items()
if not files_to_check <= fs
for f in sorted(files_to_check - fs)]
for u, f in missing_files:
print('%s - %s' % (u, f))
rc = rc | 1
# find outdated files
def age(u, f, now = datetime.now()):
fp = filepath(u, f)
t = datetime.fromtimestamp(os.path.getmtime(fp))
return now - t
max_age = 1
outdated_files = [(u, f) for u, fs in grouped_files.items()
for f in sorted(files_to_check & fs)
if age(u, f) >= timedelta(days=max_age)]
for u, f in outdated_files:
print("%s ! %s is %s days old" % (u, f, age(u, f).days))
rc = rc | 2
# exit with code
sys.exit(rc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment