1#! /usr/bin/env python 2 3# Watch line printer queue(s). 4# Intended for BSD 4.3 lpq. 5 6import os 7import sys 8import time 9 10DEF_PRINTER = 'psc' 11DEF_DELAY = 10 12 13def main(): 14 delay = DEF_DELAY # XXX Use getopt() later 15 try: 16 thisuser = os.environ['LOGNAME'] 17 except: 18 thisuser = os.environ['USER'] 19 printers = sys.argv[1:] 20 if printers: 21 # Strip '-P' from printer names just in case 22 # the user specified it... 23 for i, name in enumerate(printers): 24 if name[:2] == '-P': 25 printers[i] = name[2:] 26 else: 27 if os.environ.has_key('PRINTER'): 28 printers = [os.environ['PRINTER']] 29 else: 30 printers = [DEF_PRINTER] 31 32 clearhome = os.popen('clear', 'r').read() 33 34 while True: 35 text = clearhome 36 for name in printers: 37 text += makestatus(name, thisuser) + '\n' 38 print text 39 time.sleep(delay) 40 41def makestatus(name, thisuser): 42 pipe = os.popen('lpq -P' + name + ' 2>&1', 'r') 43 lines = [] 44 users = {} 45 aheadbytes = 0 46 aheadjobs = 0 47 userseen = False 48 totalbytes = 0 49 totaljobs = 0 50 for line in pipe: 51 fields = line.split() 52 n = len(fields) 53 if len(fields) >= 6 and fields[n-1] == 'bytes': 54 rank, user, job = fields[0:3] 55 files = fields[3:-2] 56 bytes = int(fields[n-2]) 57 if user == thisuser: 58 userseen = True 59 elif not userseen: 60 aheadbytes += bytes 61 aheadjobs += 1 62 totalbytes += bytes 63 totaljobs += 1 64 ujobs, ubytes = users.get(user, (0, 0)) 65 ujobs += 1 66 ubytes += bytes 67 users[user] = ujobs, ubytes 68 else: 69 if fields and fields[0] != 'Rank': 70 line = line.strip() 71 if line == 'no entries': 72 line = name + ': idle' 73 elif line[-22:] == ' is ready and printing': 74 line = name 75 lines.append(line) 76 77 if totaljobs: 78 line = '%d K' % ((totalbytes+1023) // 1024) 79 if totaljobs != len(users): 80 line += ' (%d jobs)' % totaljobs 81 if len(users) == 1: 82 line += ' for %s' % (users.keys()[0],) 83 else: 84 line += ' for %d users' % len(users) 85 if userseen: 86 if aheadjobs == 0: 87 line += ' (%s first)' % thisuser 88 else: 89 line += ' (%d K before %s)' % ( 90 (aheadbytes+1023) // 1024, thisuser) 91 lines.append(line) 92 93 sts = pipe.close() 94 if sts: 95 lines.append('lpq exit status %r' % (sts,)) 96 return ': '.join(lines) 97 98if __name__ == "__main__": 99 try: 100 main() 101 except KeyboardInterrupt: 102 pass 103