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.

2 Answers 2

11

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

4
  • A bit awkward, but yeah, that'd be the way to go if it's not possible.
    – DavidC
    May 6, 2015 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, 2015 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, 2015 at 7: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, 2016 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.