An atq script that might be useful

So as I mentioned in the last post – I’m in the process of leaving my job at Royal Holloway, this has obviously involved a bit of handover work and I took the time to make some of it more widely available.  If you are a regular reader this is NOT a post for you – this is a very specialist one that will probably only appeal to people arriving from Google.

I use ‘at’ to schedule jobs and ‘atq’ to display the scheduled jobs. But it mildly irritates me in that I have to look up each job individually.  I wrote a Python script to display the scheduled job under the scheduled time.

(In my world all the commands will begin ‘task’ – you would modify the script in the obvious way)

So instead of

stafflinux$atq
 8 Mon Aug 18 09:00:00 2014 a joseph
 10 Tue Aug 19 09:00:00 2014 a joseph
 15 Thu Aug 21 09:00:00 2014 a joseph
 12 Fri Aug 22 09:00:00 2014 a joseph
 9 Thu Aug 21 09:00:00 2014 a joseph
 14 Sat Aug 30 09:00:00 2014 a joseph
 7 Sun Aug 17 09:00:00 2014 a joseph
 6 Mon Aug 18 09:00:00 2014 a joseph
 11 Sat Aug 30 09:00:00 2014 a joseph
 stafflinux$

My script produces

stafflinux$./atscript.py 
8  Mon Aug 18 09:00:00 2014 a joseph
task "buy a four-way plug adapter" 
task "see guy about meeting" 
-----------------------------------------
10  Tue Aug 19 09:00:00 2014 a joseph
task "bring back personal effects from office" 
-----------------------------------------
15  Thu Aug 21 09:00:00 2014 a joseph
task "book tickets for next week"
-----------------------------------------

It sorts the output by date effectively (as in, it sorts by date that you expect things will be executed rather than the date things where added, which is the default).

The code looks like this, and I’m grateful to the stackoverflow guys for helping me to tighten it up considerably.

#!/usr/bin/env python

import subprocess
import re
import datetime
from operator import itemgetter

re_job_number = re.compile(r'\d+')
joblist =[]
for atq_line in subprocess.Popen(['atq'], stdout=subprocess.PIPE).stdout:
    job_number = re_job_number.search(atq_line).group()
    date_string= atq_line[len(job_number):].strip()
    result=""
    for at_line in subprocess.Popen(['at', '-c', job_number], stdout=subprocess.
PIPE).stdout:
        if at_line.startswith('task '):
            result=result+at_line.strip()+'\n'
    result=result+ '-' * 40
    item=(date_string,  result)
    joblist.append(item)
joblist.sort(key=lambda item: datetime.datetime.strptime(item[0], '%a %b %d %H:%
M:%S %Y a joseph'))

for x in joblist: 
   print x[0]
   print x[1]

Leave a Reply