#!/usr/bin/env python import os import sys from encodings import aliases try: set except NameError: from sets import Set as set def usage(): print """Usage: %s inencoding outencoding [filein|-] [fileout|-] List of supported encodings: http://docs.python.org/lib/standard-encodings.html Usage2: %s [list|listencondings] Examples: echo abcd | pyrecode ascii base64 - - pyrecode latin1 utf8 myscript.py out.py """ % ( os.path.basename(sys.argv[0]), os.path.basename(sys.argv[0]) ) def error(exc, mystr): print exc part=mystr[max(exc.start-10, 0):min(exc.end+10, len(mystr))] print "Error in part: start: %s end: %s len(): %s %r" % ( exc.start, exc.end, len(mystr), part) def main(): if len(sys.argv)==2 and sys.argv[1].startswith("list"): encs=list(set(aliases.aliases.values())) encs.sort() print ' '.join(encs) sys.exit(0) if not len(sys.argv)==5: usage() sys.exit(2) inenc, outenc, filein, fileout = sys.argv[1:] if filein=="-": fd=sys.stdin else: fd=open(filein, "rb") bytesin=fd.read() fd.close() try: unistr=bytesin.decode(inenc) except UnicodeDecodeError, exc: print "Error while decoding (%s to unicode)" % inenc error(exc, bytesin) sys.exit(1) try: outstr=unistr.encode(outenc) except UnicodeEncodeError, exc: print "Error while encoding (unicode to %s)" % outenc error(exc, unistr) sys.exit(1) if fileout=="-": fd=sys.stdout else: fd=open(fileout, "wb") fd.write(outstr) fd.close() if __name__=="__main__": main()