-#! /usr/bin/env python
+#! /usr/bin/env python3
"Recode to default charset"
import sys
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"))