Plex plugin to to play various online streams (mostly Latvian).

chardetect.py 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/usr/bin/env python
  2. """
  3. Script which takes one or more file paths and reports on their detected
  4. encodings
  5. Example::
  6. % chardetect somefile someotherfile
  7. somefile: windows-1252 with confidence 0.5
  8. someotherfile: ascii with confidence 1.0
  9. If no paths are provided, it takes its input from stdin.
  10. """
  11. from __future__ import absolute_import, print_function, unicode_literals
  12. import argparse
  13. import sys
  14. from io import open
  15. from chardet import __version__
  16. from chardet.universaldetector import UniversalDetector
  17. def description_of(lines, name='stdin'):
  18. """
  19. Return a string describing the probable encoding of a file or
  20. list of strings.
  21. :param lines: The lines to get the encoding of.
  22. :type lines: Iterable of bytes
  23. :param name: Name of file or collection of lines
  24. :type name: str
  25. """
  26. u = UniversalDetector()
  27. for line in lines:
  28. u.feed(line)
  29. u.close()
  30. result = u.result
  31. if result['encoding']:
  32. return '{0}: {1} with confidence {2}'.format(name, result['encoding'],
  33. result['confidence'])
  34. else:
  35. return '{0}: no result'.format(name)
  36. def main(argv=None):
  37. '''
  38. Handles command line arguments and gets things started.
  39. :param argv: List of arguments, as if specified on the command-line.
  40. If None, ``sys.argv[1:]`` is used instead.
  41. :type argv: list of str
  42. '''
  43. # Get command line arguments
  44. parser = argparse.ArgumentParser(
  45. description="Takes one or more file paths and reports their detected \
  46. encodings",
  47. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  48. conflict_handler='resolve')
  49. parser.add_argument('input',
  50. help='File whose encoding we would like to determine.',
  51. type=argparse.FileType('rb'), nargs='*',
  52. default=[sys.stdin])
  53. parser.add_argument('--version', action='version',
  54. version='%(prog)s {0}'.format(__version__))
  55. args = parser.parse_args(argv)
  56. for f in args.input:
  57. if f.isatty():
  58. print("You are running chardetect interactively. Press " +
  59. "CTRL-D twice at the start of a blank line to signal the " +
  60. "end of your input. If you want help, run chardetect " +
  61. "--help\n", file=sys.stderr)
  62. print(description_of(f, f.name))
  63. if __name__ == '__main__':
  64. main()