Skip to content

Commit 2e38107

Browse files
committed
Restructured try/except block in setup_logging.setup_logging() to avoid catching any UnsupportedOperation errors thrown by code other than sys.stdout.fileno().
1 parent 97e70c7 commit 2e38107

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

labscript_utils/setup_logging.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,16 @@ def setup_logging(program_name, log_level=logging.DEBUG, terminal_level=logging.
5555
handler.setLevel(log_level)
5656
logger.addHandler(handler)
5757
try:
58+
# Check that sys.stdout.fileno is callable, which is needed below. It is NOT
59+
# callable in Jupyter notebooks.
60+
sys.stdout.fileno()
61+
except UnsupportedOperation:
62+
# In this case the code is likely being run from a Jupyter notebook, warn the
63+
# user that log messages won't be printed to stdout or stderr.
64+
warnings.warn(
65+
"Logging to stdout and stderr is disabled. See the log files for log messages."
66+
)
67+
else:
5868
if sys.stdout is not None and sys.stdout.fileno() >= 0:
5969
stdout_handler = logging.StreamHandler(sys.stdout)
6070
stdout_handler.setFormatter(formatter)
@@ -71,11 +81,5 @@ def setup_logging(program_name, log_level=logging.DEBUG, terminal_level=logging.
7181
# Prevent bug on windows where writing to stdout without a command
7282
# window causes a crash:
7383
sys.stdout = sys.stderr = open(os.devnull, 'w')
74-
except UnsupportedOperation:
75-
# Special handling for Jupyter notebook kernels where sys.stdout.fileno is not
76-
# callable.
77-
warnings.warn(
78-
"Logging to stdout and stderr is disabled. See the log files for log messages."
79-
)
8084
logger.setLevel(logging.DEBUG)
8185
return logger

0 commit comments

Comments
 (0)