Package osh :: Package command :: Module sort
[frames] | no frames]

Source Code for Module osh.command.sort

 1  # osh 
 2  # Copyright (C) Jack Orenstein <jao@geophile.com> 
 3  # 
 4  # This program is free software; you can redistribute it and/or modify 
 5  # it under the terms of the GNU General Public License as published by 
 6  # the Free Software Foundation; either version 2 of the License, or 
 7  # (at your option) any later version. 
 8  # 
 9  # This program is distributed in the hope that it will be useful, 
10  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
11  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
12  # GNU General Public License for more details. 
13  # 
14  # You should have received a copy of the GNU General Public License 
15  # along with this program; if not, write to the Free Software 
16  # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 
17   
18  """C{sort [FUNCTION]} 
19   
20  Input objects are sorted before being written to output.  If 
21  C{FUNCTION} is not provided then input objects are sorted using the 
22  default ordering (i.e., based on the C{cmp} function). 
23   
24  If C{FUNCTION} is provided, then sorting is done by applying C{cmp} to 
25  values obtained by applying C{FUNCTION} to the input objects. 
26  """ 
27   
28  import osh.core 
29   
30  # CLI 
31 -def _sort():
32 return _Sort()
33 34 # CLI
35 -def sort(function = None):
36 """Input objects are sorted before being written to output. If 37 C{function} is not provided then input objects are sorted using the 38 default ordering (i.e., based on the C{cmp} function). 39 If C{function} is provided, then sorting is done by applying C{cmp} to 40 values obtained by applying C{function} to the input objects. 41 """ 42 args = [] 43 if function: 44 args.append(function) 45 return _Sort().process_args(*args)
46
47 -class _Sort(osh.core.Op):
48 49 _key = None 50 _list = None 51 52 53 # object interface 54
55 - def __init__(self):
56 osh.core.Op.__init__(self, '', (0, 1))
57 58 59 # BaseOp interface 60
61 - def doc(self):
62 return __doc__
63
64 - def setup(self):
65 args = self.args() 66 if args.has_next(): 67 self._key = args.next_function() 68 if args.has_next(): 69 self.usage() 70 self._list = []
71
72 - def receive(self, object):
73 self._list.append(object)
74
75 - def receive_complete(self):
76 key = self._key 77 if key: 78 # Attach the keys, sort by the key, then detach the key. 79 self._list = [(key(*object), object) for object in self._list] 80 self._list.sort(lambda x, y: cmp(x[0], y[0])) 81 self._list = [t[1] for t in self._list] 82 else: 83 self._list.sort() 84 for object in self._list: 85 self.send(object) 86 self.send_complete()
87