Skip to content

Commit b711923

Browse files
committed
setup_logging.py is now more Jupyter-friendly.
1 parent d5dfea7 commit b711923

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

labscript_utils/setup_logging.py

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# #
1212
#####################################################################
1313
import sys, os
14+
from io import UnsupportedOperation
1415
import logging, logging.handlers
1516
from labscript_utils.ls_zprocess import Handler, ensure_connected_to_zlog
1617

@@ -52,21 +53,26 @@ def setup_logging(program_name, log_level=logging.DEBUG, terminal_level=logging.
5253
handler.setFormatter(formatter)
5354
handler.setLevel(log_level)
5455
logger.addHandler(handler)
55-
if sys.stdout is not None and sys.stdout.fileno() >= 0:
56-
stdout_handler = logging.StreamHandler(sys.stdout)
57-
stdout_handler.setFormatter(formatter)
58-
stdout_handler.setLevel(terminal_level)
59-
logger.addHandler(stdout_handler)
60-
if sys.stderr is not None and sys.stderr.fileno() >= 0:
61-
# Send warnings and greater to stderr instead of stdout:
62-
stdout_handler.addFilter(LessThanFilter(logging.WARNING))
63-
sterr_handler = logging.StreamHandler(sys.stderr)
64-
sterr_handler.setFormatter(formatter)
65-
sterr_handler.setLevel(logging.WARNING)
66-
logger.addHandler(sterr_handler)
67-
else:
68-
# Prevent bug on windows where writing to stdout without a command
69-
# window causes a crash:
70-
sys.stdout = sys.stderr = open(os.devnull, 'w')
56+
try:
57+
if sys.stdout is not None and sys.stdout.fileno() >= 0:
58+
stdout_handler = logging.StreamHandler(sys.stdout)
59+
stdout_handler.setFormatter(formatter)
60+
stdout_handler.setLevel(terminal_level)
61+
logger.addHandler(stdout_handler)
62+
if sys.stderr is not None and sys.stderr.fileno() >= 0:
63+
# Send warnings and greater to stderr instead of stdout:
64+
stdout_handler.addFilter(LessThanFilter(logging.WARNING))
65+
sterr_handler = logging.StreamHandler(sys.stderr)
66+
sterr_handler.setFormatter(formatter)
67+
sterr_handler.setLevel(logging.WARNING)
68+
logger.addHandler(sterr_handler)
69+
else:
70+
# Prevent bug on windows where writing to stdout without a command
71+
# window causes a crash:
72+
sys.stdout = sys.stderr = open(os.devnull, 'w')
73+
except UnsupportedOperation:
74+
# Special handling for Jupyter notebook kernels where sys.stdout.fileno is not
75+
# callable.
76+
pass
7177
logger.setLevel(logging.DEBUG)
7278
return logger

0 commit comments

Comments
 (0)