|
19 | 19 | reset() |
20 | 20 |
|
21 | 21 |
|
| 22 | +def __stdin_pipe(): |
| 23 | + """ Stdin pipe read function. """ |
| 24 | + try: |
| 25 | + with open(0, 'rb') as f: |
| 26 | + for l in f: |
| 27 | + yield l |
| 28 | + except TypeError: |
| 29 | + import sys |
| 30 | + for l in sys.stdin: |
| 31 | + yield l |
| 32 | + |
| 33 | + |
22 | 34 | def main(): |
23 | 35 | import argparse, os |
24 | 36 | parser = argparse.ArgumentParser() |
25 | | - group = parser.add_mutually_exclusive_group(required=True) |
26 | | - group.add_argument("-d", "--decode") |
27 | | - group.add_argument("-e", "--encode") |
| 37 | + parser.add_argument("encoding") |
| 38 | + parser.add_argument("-d", "--decode", action="store_true") |
| 39 | + parser.add_argument("-e", "--errors", default="strict", |
| 40 | + choices=["ignore", "replace", "strict"], |
| 41 | + help="ignore|replace|strict") |
28 | 42 | parser.add_argument("-i", "--input-file", dest="infile") |
29 | 43 | parser.add_argument("-o", "--output-file", dest="outfile") |
30 | 44 | args = parser.parse_args() |
| 45 | + # handle input file or stdin |
31 | 46 | if os.path.isfile(args.infile): |
32 | | - with codecs.open(f, encoding=args.decode) as fin: |
33 | | - c = fin.read() |
| 47 | + with open(args.infile) as f: |
| 48 | + c = f.read() |
34 | 49 | else: |
35 | | - pass #FIXME: take from stdin |
| 50 | + c = "" |
| 51 | + for line in __stdin_pipe(): |
| 52 | + c += codecs.encode(line, errors=args.errors) |
| 53 | + # encode or decode |
| 54 | + c = getattr(codext, ["encode", "decode"][args.decode])\ |
| 55 | + (c, args.encoding, args.errors) |
| 56 | + # hanbdle output file or stdout |
36 | 57 | if args.outfile is None: |
37 | 58 | print(c) |
38 | 59 | else: |
39 | | - with open(args.outfile, 'w') as fout: |
40 | | - fout.write(c) |
| 60 | + with open(args.outfile, 'w') as f: |
| 61 | + f.write(c) |
0 commit comments