Get a list of all the encodings Python can encode to

后端 未结 9 1290
暗喜
暗喜 2020-11-28 03:19

I am writing a script that will try encoding bytes into many different encodings in Python 2.6. Is there some way to get a list of available encodings that I can iterate ove

9条回答
  •  悲&欢浪女
    2020-11-28 04:10

    Here's a programmatic way to list all the encodings defined in the stdlib encodings package, note that this won't list user defined encodings. This combines some of the tricks in the other answers but actually produces a working list using the codec's canonical name.

    import encodings
    import pkgutil
    import pprint
    
    
    all_encodings = set()
    
    for _, modname, _ in pkgutil.iter_modules(
            encodings.__path__, encodings.__name__ + '.',
    ):
        try:
            mod = __import__(modname, fromlist=[str('__trash')])
        except (ImportError, LookupError):
            # A few encodings are platform specific: mcbs, cp65001
            # print('skip {}'.format(modname))
            pass
    
        try:
            all_encodings.add(mod.getregentry().name)
        except AttributeError as e:
            # the `aliases` module doensn't actually provide a codec
            # print('skip {}'.format(modname))
            if 'regentry' not in str(e):
                raise
    
    pprint.pprint(sorted(all_encodings))
    

提交回复
热议问题