1# vim:ts=4 sw=4 expandtab softtabstop=4 2from __future__ import print_function 3import argparse 4import locale 5import os 6import sys 7 8from unidecode import unidecode 9 10PY3 = sys.version_info[0] >= 3 11 12def fatal(msg): 13 sys.stderr.write(msg + "\n") 14 sys.exit(1) 15 16def main(): 17 default_encoding = locale.getpreferredencoding() 18 19 parser = argparse.ArgumentParser( 20 description="Transliterate Unicode text into ASCII. FILE is path to file to transliterate. " 21 "Standard input is used if FILE is omitted and -c is not specified.") 22 parser.add_argument('-e', '--encoding', metavar='ENCODING', default=default_encoding, 23 help='Specify an encoding (default is %s)' % (default_encoding,)) 24 parser.add_argument('-c', metavar='TEXT', dest='text', 25 help='Transliterate TEXT instead of FILE') 26 parser.add_argument('path', nargs='?', metavar='FILE') 27 28 args = parser.parse_args() 29 30 encoding = args.encoding 31 32 if args.path: 33 if args.text: 34 fatal("Can't use both FILE and -c option") 35 else: 36 with open(args.path, 'rb') as f: 37 stream = f.read() 38 elif args.text: 39 if PY3: 40 stream = os.fsencode(args.text) 41 else: 42 stream = args.text 43 # add a newline to the string if it comes from the 44 # command line so that the result is printed nicely 45 # on the console. 46 stream += b'\n' 47 else: 48 if PY3: 49 stream = sys.stdin.buffer.read() 50 else: 51 stream = sys.stdin.read() 52 53 try: 54 stream = stream.decode(encoding) 55 except UnicodeDecodeError as e: 56 fatal('Unable to decode input: %s, start: %d, end: %d' % (e.reason, e.start, e.end)) 57 58 sys.stdout.write(unidecode(stream)) 59