Logging while nbconvert execute

2024/10/12 20:23:11

I have a Jupyter notebook that needs to run from the command line. For this I have the following command:

jupyter nbconvert --execute my_jupyter_notebook.ipynb --to python

This command creates a python script and then executes it. However, I'm using the logging library in Python to log certain events. When it executes the script from the command above, nothing can be seen on the terminal.

However, when I execute manually the converted jupyter, like below, I can see all the logs on my terminal:

python3 my_jupyter_notebook.py

I've tried adding extra arguments like --debug and --stdout but those just output all the code, not just the logs. Is it possible to output on the terminal the results of logging while doing an nbconvert execute command?

Answer

Jupyter modifies the sys.stderr and sys.stdout streams so they no longer point to the "standard" stderr and stdout (pun intended). However, they store a copy to the original file handle under _original_stdstream_copy, and you can create a log handler that explicitly writes to the original stream.

def console_handler(stream='stdout'):"""Create a handler for logging to the original console."""assert stream in {'stdout', 'stderr'}, "stream must be one of 'stdin' or 'stdout'"# Get the file handle of the original std stream.fh = getattr(sys, stream)._original_stdstream_copy# Create a writable IO stream.stream = io.TextIOWrapper(io.FileIO(fh, 'w'))# Set up a stream handler.return logging.StreamHandler(stream)

You can use the function as follows.

import logginglogging.basicConfig(...)  # Or some more sophisticated setup.
logger = logging.getLogger('myLogger')
logger.add_handler(console_handler())
logger.error('something went wrong')  # This will write to stderr.
https://en.xdnf.cn/q/69616.html

Related Q&A

How to provide input for a TensorFlow DNNRegressor in Java?

I managed to write a TensorFlow python program with a DNNRegressor. I have trained the model and is able to get a prediction from the model in Python by manually created input (constant tensors). I hav…

Adding breakpoint command lists in GDB controlled from Python script

Im using Python to control GDB via batch commands. Heres how Im calling GDB:$ gdb --batch --command=cmd.gdb myprogramThe cmd.gdb listing just contains the line calling the Python scriptsource cmd.pyAnd…

Getting the maximum accuracy for a binary probabilistic classifier in scikit-learn

Is there any built-in function to get the maximum accuracy for a binary probabilistic classifier in scikit-learn?E.g. to get the maximum F1-score I do:# AUCPR precision, recall, thresholds = sklearn.m…

Pydantic does not validate when assigning a number to a string

When assigning an incorrect attribute to a Pydantic model field, no validation error occurs. from pydantic import BaseModelclass pyUser(BaseModel):username: strclass Config:validate_all = Truevalidate_…

PyUsb USB Barcode Scanner

Im trying to output a string from a barcode or qrcode using a Honeywell USB 3310g scanner in Ubuntu. I have libusb and a library called metro-usb (http://gitorious.org/other/metro-usb) which are enabli…

Count unique dates in pandas dataframe

I have a dataframe of surface weather observations (fzraHrObs) organized by a station identifier code and date. fzraHrObs has several columns of weather data. The station code and date (datetime object…

Miniforge / VScode - Python is not installed and virtualenv is not found

I have been stuck on this issue for several days, so any help is greatly appreciated. I recently had to move away from Anaconda (due to their change in the commercial policy) and decided to try Minifo…

How to merge pandas table by regex

I am wondering if there a fast way to merge two pandas tables by the regular expression in python .For example: table A col1 col2 1 apple_3dollars_5 2 apple_2dollar_4 1 o…

Scipy Optimize is only returning x0, only completing one iteration

I am using scipy optimize to get the minimum value on the following function: def randomForest_b(a,b,c,d,e):return abs(rf_diff.predict([[a,b,c,d,e]]))I eventually want to be able to get the optimal val…

Order of sess.run([op1, op2...]) in Tensorflow

I wonder whats the running order of the op list in sess.run(ops_list, ...). for example:for a typical classification scenario: _, loss = sess.run([train_op, loss_op]), if train_op run first,then the lo…