Skip to content

Commit

Permalink
Rework use of application log file
Browse files Browse the repository at this point in the history
- Running under pythonw (no console), redirect stdout/stderr to a file
to avoid the programming blocking when it tries to write to them.
- Running in the console, only print the traceback to the file on an
uncaught exception.
- Also print exception to stderr as normal if there's a console

Closes gh-36
  • Loading branch information
takluyver committed Feb 21, 2015
1 parent 0584615 commit 4e2813a
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions nsist/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,14 +161,23 @@ def fetch_pylauncher(self):
sys.path.insert(0, pkgdir)
os.environ['PYTHONPATH'] = pkgdir + os.pathsep + os.environ.get('PYTHONPATH', '')
appdata = os.environ.get('APPDATA', None)
def excepthook(etype, value, tb):
"Write unhandled exceptions to a file rather than exiting silently."
import traceback
with open(os.path.join(appdata, script+'.log'), 'w') as f:
traceback.print_exception(etype, value, tb, file=f)
if appdata:
# APPDATA should always be set, but in case it isn't, try user home
# If none of APPDATA, HOME, USERPROFILE or HOMEPATH are set, this will fail.
appdata = os.environ.get('APPDATA', None) or os.path.expanduser('~')
if 'pythonw' in sys.executable:
# Running with no console - send all stdstream output to a file.
kw = {{'errors': 'replace'}} if (sys.version_info[0] >= 3) else {{}}
sys.stdout = sys.stderr = open(os.path.join(appdata, script+'.log'), 'w', **kw)
else:
# In a console. But if the console was started just for this program, it
# will close as soon as we exit, so write the traceback to a file as well.
def excepthook(etype, value, tb):
"Write unhandled exceptions to a file and to stderr."
import traceback
traceback.print_exception(etype, value, tb)
with open(os.path.join(appdata, script+'.log'), 'w') as f:
traceback.print_exception(etype, value, tb, file=f)
sys.excepthook = excepthook
{extra_preamble}
Expand Down

0 comments on commit 4e2813a

Please sign in to comment.