CUPS Purging not-completed print jobs older than..

When working with CUPS using remote print queues, you may find that the remote printer is not always available, has timed out, ran out of paper, has a paper jam, etc. Sometimes this causes a job to ‘not-complete’ and when running ‘lpstat -o’, you see old print jobs.

We put together a quick script to auto-purge these jobs.  Hopefully this helps someone in the future.

Please let us know if you found this useful, or if you have any suggested changes.

# Purge print jobs that are not-complete and older than 10 days.

from datetime import date, timedelta, datetime
import time
import os


for line in os.popen('/usr/bin/lpstat -o').readlines():
    data = line.strip().split()

    #15 Apr 2008 12:00:00
    date_time=data[4]+" "+data[5]+" "+data[6]+" 12:00:00"
    pattern = '%d %b %Y %H:%M:%S'
    epoch_job = int(time.mktime(time.strptime(date_time, pattern)))

    difference=epoch_today - epoch_job

    if difference > date_difference:
        print "Canceling pending job: "+str(job[-1])
        os.popen('/usr/bin/cancel '+str(job[-1]))