pib / q (http://blog.paulbonser.com/2009/04/21/q-textual-queue-manager/)
A small, simple comandline program and Python module for managing queues of text in files.
| commit 0: | 05b1d28ca306 |
| branch: | default |
inital version allows pushing of items to a queue and viewing the top item
11 months ago
Changed (Δ1.6 KB):
raw changeset »
q.py (60 lines added, 0 lines removed)
1 |
#!/usr/bin/env python |
|
2 |
import os |
|
3 |
||
4 |
def next(qfilename, args): |
|
5 |
"""(default) Return the top item in the queue""" |
|
6 |
return open(qfilename, 'r').readline() |
|
7 |
||
8 |
def push(qfilename, args): |
|
9 |
"""Add one or more lines to the queue""" |
|
10 |
qfile = open(qfilename, 'r') |
|
11 |
current_lines = qfile.readlines() |
|
12 |
qfile.close() |
|
13 |
qfile_tmp = open(qfilename + '.tmp', 'w') |
|
14 |
qfile_tmp.writelines([line + '\n' for line in args] + current_lines) |
|
15 |
qfile_tmp.flush() |
|
16 |
qfile_tmp.close() |
|
17 |
os.rename(qfilename + '.tmp', qfilename) |
|
18 |
return args[0] |
|
19 |
||
20 |
def _command_list(): |
|
21 |
funcs = globals() |
|
22 |
return dict([(command, funcs[command]) for command in funcs if command[0] != '_']) |
|
23 |
||
24 |
def _commandline_usage(script_name): |
|
25 |
print 'usage:', script_name, 'queuename [command [params]]' |
|
26 |
print ' commands:' |
|
27 |
commands = _command_list() |
|
28 |
for command in commands: |
|
29 |
print ' ', command, '-', commands[command].__doc__ |
|
30 |
||
31 |
||
32 |
def _main(): |
|
33 |
import sys |
|
34 |
arg_count = len(sys.argv) |
|
35 |
if arg_count < 2: |
|
36 |
return _commandline_usage(sys.argv[0]) |
|
37 |
||
38 |
qdir = os.path.expanduser('~') + '/.q' |
|
39 |
qfilename = qdir + '/' + sys.argv[1] |
|
40 |
if arg_count < 3: |
|
41 |
command_name = 'next' |
|
42 |
else: |
|
43 |
command_name = sys.argv[2] |
|
44 |
||
45 |
try: |
|
46 |
command = _command_list()[command_name] |
|
47 |
except NameError, e: |
|
48 |
print e |
|
49 |
return _commandline_usage(sys.argv[0]) |
|
50 |
||
51 |
||
52 |
if not os.path.exists(qdir): |
|
53 |
os.mkdir(qdir) |
|
54 |
if not os.path.exists(qfilename): |
|
55 |
open(qfilename, 'w+').close() |
|
56 |
||
57 |
print command(qfilename, sys.argv[3:]), |
|
58 |
||
59 |
if __name__=='__main__': |
|
60 |
_main() |
