Forráskód Böngészése

Rework use of application log file

- 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
Thomas Kluyver 10 éve
szülő
commit
4e2813af9d
1 módosított fájl, 17 hozzáadás és 8 törlés
  1. 17 8
      nsist/__init__.py

+ 17 - 8
nsist/__init__.py

@@ -161,14 +161,23 @@ pkgdir = os.path.join(scriptdir, 'pkgs')
 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}