pythonjupyter-notebookcommand-line-argumentspapermill

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?


Solution

  • If the goal is to run a notebook with configurable arguments passed from commandline, I think the easiest way is to use environment variables, like this:

    NB_ARGS=some_args jupyter nbconvert --execute --to html --template full some_notebook.ipynb
    

    Then in the notebook, you can import os and use os.environ['NB_ARGS']. The variable value can be some text that contains key-value pairs or json for example.