Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2@file 

3@brief A function to read a script and reading the encoding on the first line. 

4""" 

5import os 

6 

7 

8def detect_encoding(filename): 

9 """ 

10 Guesses the encoding from ``# -*- coding: ...``. 

11 

12 @param filename filename 

13 @return encoding or None 

14 """ 

15 if isinstance(filename, str) and os.path.exists(filename): 

16 with open(filename, 'rb') as f: 

17 enc = f.read(30) 

18 elif isinstance(filename, bytes): 

19 enc = filename 

20 else: 

21 raise TypeError("Unexpected type %r." % type(filename)) 

22 s = enc.decode("ascii", errors="ignore") 

23 s = s.replace(" ", "").replace("\r", "") 

24 d = "#-*-coding:" 

25 if s.startswith(d): 

26 s = s[len(d):] 

27 i = s.find("-*-") 

28 if i > 0: 

29 return s[:i] 

30 return None 

31 

32 

33def open_script(filename, mode="r"): 

34 """ 

35 Open a filename but read the encoding from the first line. 

36 

37 @param filename filename 

38 @param mode r, only r 

39 @return stream 

40 """ 

41 if mode == "r": 

42 encoding = detect_encoding(filename) 

43 return open(filename, mode, encoding=encoding) 

44 raise ValueError( # pragma: no cover 

45 "This function only works for mode='r'.")