Skip to content
Advertisement

Passing command line arguments to argv in jupyter/ipython notebook

I’m wondering if it’s possible to populate sys.argv (or some other structure) with command line arguments in a jupyter/ipython notebook, similar to how it’s done through a python script.

For instance, if I were to run a python script as follows:

python test.py False

Then sys.argv would contain the argument False. But if I run a jupyter notebook in a similar manner:

jupyter notebook test.ipynb False

Then the command line argument gets lost. Is there any way to access this argument from within the notebook itself?

Advertisement

Answer

After a lot of looking around I found very cumbersome, custom libraries, but solved it with a few lines of code which I thought was pretty slick. I used nbconvert to end up with an html report as output that contains all graphics and markdown from the notebook, but accepts command line parameters just as always through a minimal python wrapper:

The python file test_args.py (which takes command line params as normal):

JavaScript

The notebook contains:

JavaScript

and I can run the python notebook with arguments parsed as usual:

JavaScript

I tend to paste the block with argparse calls into the python wrapper so that command line errors are caught by the python script and -h works properly.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement