ecd0163be726bf513048c69d47770527829e8143
[sdc/sdc-distribution-client.git] /
1 #!/usr/bin/env python
2 """
3 Script which takes one or more file paths and reports on their detected
4 encodings
5
6 Example::
7
8     % chardetect somefile someotherfile
9     somefile: windows-1252 with confidence 0.5
10     someotherfile: ascii with confidence 1.0
11
12 If no paths are provided, it takes its input from stdin.
13
14 """
15 from io import open
16 from sys import argv, stdin
17
18 from chardet.universaldetector import UniversalDetector
19
20
21 def description_of(file, name='stdin'):
22     """Return a string describing the probable encoding of a file."""
23     u = UniversalDetector()
24     for line in file:
25         u.feed(line)
26     u.close()
27     result = u.result
28     if result['encoding']:
29         return '%s: %s with confidence %s' % (name,
30                                               result['encoding'],
31                                               result['confidence'])
32     else:
33         return '%s: no result' % name
34
35
36 def main():
37     if len(argv) <= 1:
38         print(description_of(stdin))
39     else:
40         for path in argv[1:]:
41             with open(path, 'rb') as f:
42                 print(description_of(f, path))
43
44
45 if __name__ == '__main__':
46     main()