Debian Codegraph @

misc/py2exe/boot_common.py

raw
1 # Common py2exe boot script - executed for all target types.
2
3 # When we are a windows_exe we have no console, and writing to
4 # sys.stderr or sys.stdout will sooner or later raise an exception,
5 # and tracebacks will be lost anyway (see explanation below).
6 #
7 # We assume that output to sys.stdout can go to the bitsink, but we
8 # *want* to see tracebacks. So we redirect sys.stdout into an object
9 # with a write method doing nothing, and sys.stderr into a logfile
10 # having the same name as the executable, with '.log' appended.
11 #
12 # We only open the logfile if something is written to sys.stderr.
13 #
14 # If the logfile cannot be opened for *any* reason, we have no choice
15 # but silently ignore the error.
16 #
17 # More elaborate explanation on why this is needed:
18 #
19 # The sys.stdout and sys.stderr that GUI programs get (from Windows) are
20 # more than useless. This is not a py2exe problem, pythonw.exe behaves
21 # in the same way.
22 #
23 # To demonstrate, run this program with pythonw.exe:
24 #
25 # import sys
26 # sys.stderr = open("out.log", "w")
27 # for i in range(10000):
28 # print i
29 #
30 # and open the 'out.log' file. It contains this:
31 #
32 # Traceback (most recent call last):
33 # File "out.py", line 6, in ?
34 # print i
35 # IOError: [Errno 9] Bad file descriptor
36 #
37 # In other words, after printing a certain number of bytes to the
38 # system-supplied sys.stdout (or sys.stderr) an exception will be raised.
39 #
40
41 import sys
42 if sys.frozen == "windows_exe":
43 class Stderr:
44 encoding = None
45 softspace = 0
46 _file = None
47 _error = None
48
49 def write(self, text, alert=sys._MessageBox, fname=sys.executable + '.log'):
50 if self._file is None and self._error is None:
51 try:
52 self._file = open(fname, 'w')
53 except Exception as details:
54 self._error = details
55 if self._file is not None:
56 self._file.write(text)
57 self._file.flush()
58
59 def flush(self):
60 if self._file is not None:
61 self._file.flush()
62
63 def isatty(self):
64 return False
65
66 sys.stderr = Stderr()
67 del sys._MessageBox
68 del Stderr
69
70 class Blackhole:
71 encoding = None
72 softspace = 0
73
74 def write(self, text):
75 pass
76
77 def flush(self):
78 pass
79
80 def isatty(self):
81 return False
82
83 sys.stdout = Blackhole()
84 del Blackhole
85
86 del sys
87
88 # Disable linecache.getline() which is called by
89 # traceback.extract_stack() when an exception occurs to try and read
90 # the filenames embedded in the packaged python code. This is really
91 # annoying on windows when the d: or e: on our build box refers to
92 # someone elses removable or network drive so the getline() call
93 # causes it to ask them to insert a disk in that drive.
94 import linecache
95 def fake_getline(filename, lineno, module_globals=None):
96 return ''
97 linecache.orig_getline = linecache.getline
98 linecache.getline = fake_getline
99
100 del linecache, fake_getline