銀月の符号

Python 使い見習いの日記・雑記

Python レシピ更新、ファイルを16進ダンプする

162:ファイルを16進ダンプする」を手直し。使うものが変わったので。

  • 旧: 'Python'.encode('hex_codec')
  • 新: binascii.hexlify('Python')

hex_codec は内部で binascii.hexlify を用いている。そして hexlify 関数の使い方は簡単。ならば直接使ったほうがよいはず。 Python 3 では hex_codec がなくなっている、という問題もあることだし。

# coding: utf-8

import sys
import binascii

def hexdump(in_file=sys.stdin, out_file=sys.stdout, bufsize=8192):
    u"""ファイルを 16 進ダンプする"""

    read = in_file.read
    write = out_file.write
    hexlify = binascii.hexlify

    if hasattr(in_file, 'isatty') and in_file.isatty():
        write(hexlify(read()))
    else:
        d = read(bufsize)
        while d:
            write(hexlify(d))
            d = read(bufsize)

def main():
    import optparse
    usage = '%prog inputfile [...]'
    option_parser = optparse.OptionParser(usage=usage)
    options, args = option_parser.parse_args()

    len_args = len(args)
    if len_args == 0:
        hexdump(sys.stdin, sys.stdout)
    elif len_args == 1:
        hexdump(open(args[0], 'rb'), sys.stdout)
    else:
        for arg in args:
            sys.stdout.write(u'---------- %s ----------\n' % arg)
            try:
                f = open(arg, 'rb')
                try:
                    hexdump(f, sys.stdout)
                finally:
                    f.close()
            except IOError, e:
                sys.stdout.write(str(e))
            sys.stdout.write(u'\n')

if __name__ == '__main__':
    main()