X-Git-Url: https://git.phdru.name/?p=dotfiles.git;a=blobdiff_plain;f=bin%2Ficonv.py;h=83de413dc373ac5093e3cedfd971870676dbe6d9;hp=41631fea5bd449cd6128f4a33adbe5835c8bb8ac;hb=HEAD;hpb=c5883d2a782366c0a3468a989e756cf37dabbd46 diff --git a/bin/iconv.py b/bin/iconv.py index 41631fe..9cb164f 100755 --- a/bin/iconv.py +++ b/bin/iconv.py @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 "Recode to default charset" import sys @@ -10,19 +10,23 @@ to_charset = default_encoding options, arguments = getopt(sys.argv[1:], 'f:t:') for option, value in options: - if option == '-f': - from_charset = value - elif option == '-t': - to_charset = value + if option == '-f': + from_charset = value + elif option == '-t': + to_charset = value + +output = getattr(sys.stdout, 'buffer', sys.stdout) + if arguments: - for file in arguments: - infile = open(file) - try: - for line in infile: - sys.stdout.write(unicode(line, from_charset, "replace").encode(to_charset, "replace")) - except: - infile.close() + for file in arguments: + with open(file, 'rb') as infile: + for line in infile: + output.write( + line.decode(from_charset, "replace"). + encode(to_charset, "replace")) else: - for line in sys.stdin: - sys.stdout.write(unicode(line, from_charset, "replace").encode(to_charset, "replace")) + input = getattr(sys.stdin, 'buffer', sys.stdin) + for line in input: + output.write( + line.decode(from_charset, "replace").encode(to_charset, "replace"))