16

I'm using nbconvert to execute an iPython notebook via the command line (as in this answer):

ipython nbconvert --to=html --ExecutePreprocessor.enabled=True RunMe.ipynb

Is it possible to pass command line arguments to be accessed from within the notebook (like sys.argv)?

This would let me reuse the same notebook in different contexts.

Community
  • 1
  • 1
DavidC
  • 1,409
  • 10
  • 25

2 Answers2

11

You can access environmental variables instead. I have yet to come across a way to use command line arguments directly.

nitind
  • 19,089
  • 4
  • 34
  • 43
  • A bit awkward, but yeah, that'd be the way to go if it's not possible. – DavidC May 06 '15 at 16:15
  • Have you found a way that's possible? Because I'm loving how folks down voting this without giving a better answer. – nitind Jun 23 '15 at 20:23
  • 2
    Have not found anything better! I didn't down-vote, but my guess is no one would down-vote if you hadn't framed the answer as if there's no need for the functionality I'm asking for. (environment variables work but it's awkward!) – DavidC Jun 24 '15 at 07:05
  • 4
    Along those lines, you may use one environment variable: `NB_ARGS='--par1 val1 --par2 val2' jupyter nbconvert mynotebook.html --execute --stdout > myoutput.html` and use `argparse, os` inside the notebook, as `parser.parse_args(os.environ['NB_ARGS'])`. At least there is only one variable involved... – Mahé May 24 '16 at 17:18
2

This is my attempt at a single module for argument parsing in Python scripts and Jupyter notebooks. It only supports minimalist key=value style arguments but meets my needs.

I nbconvert it to a Python script named Args.py and use it as shown.

Then I can batch run a notebook like:

jpn mynotebook limit=5 assignment=A2

GaryBishop
  • 3,204
  • 2
  • 23
  • 19