X-Git-Url: https://git.phdru.name/?p=dotfiles.git;a=blobdiff_plain;f=bin%2Ficonv.py;h=9cb164fef0aa72bc6a2399d1ab4a988dd27d4c59;hp=83de413dc373ac5093e3cedfd971870676dbe6d9;hb=HEAD;hpb=f0344023aa21ede3b47d77559af54b97c37f328b diff --git a/bin/iconv.py b/bin/iconv.py index 83de413..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(line.decode(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(line.decode(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"))