More tweaks; notably try to insert paragraph breaks rather than a separate Python...
[python-collate.git] / pycollate
1 #!/usr/bin/env python
2
3 import os
4 import sys
5 import locale
6
7 from optparse import OptionParser
8
9 import collate
10
11 def main(argv):
12 lines = []
13 encoding = locale.getpreferredencoding()
14 try:
15 locale.setlocale(locale.LC_ALL, '')
16 except locale.Error:
17 pass
18
19 parser = OptionParser()
20 parser.add_option("-b", "--backend", dest="backend",
21 help="use backend BACKEND", metavar="BACKEND",
22 default="default")
23 parser.add_option("-l", "--locale", dest="locale",
24 help="use locale LOCALE", metavar="LOCALE",
25 default=locale.getlocale()[0])
26 parser.add_option("-e", "--encoding", dest="encoding",
27 help="use encoding ENCODING", metavar="ENCODING",
28 default=encoding)
29 parser.add_option("-d", "--diagnostics", action="store_true",
30 dest="diagnostics", help="print diagnostic information")
31
32 options, args = parser.parse_args()
33
34 if options.backend or options.locale or options.encoding:
35 backend = getattr(collate, options.backend)
36 collate.set_default(backend, options.locale, options.encoding)
37
38 if options.diagnostics:
39 print >>sys.stderr, "Backend: " + collate.default.__name__
40 print >>sys.stderr, "Locale: " + collate.collator.locale
41 print >>sys.stderr, "Encoding: " + collate.collator.encoding
42
43 if not args:
44 raise SystemExit
45
46 if not args:
47 args.append("-")
48 for filename in args:
49 if filename == "-":
50 fileobj = sys.stdin
51 else:
52 fileobj = open(filename, "rU")
53 for line in fileobj:
54 line = line.strip()
55 line = line.decode(encoding, "replace")
56 lines.append(line)
57 lines.sort(key=collate.collator.sortemekey)
58
59 for line in lines:
60 print line.encode(encoding, "replace")
61
62 if __name__ == "__main__":
63 main(sys.argv[1:])