Convert ipython notebook to directly-executable python script

Viewed 9482

I have a jupyter/ipython notebook that I am using for prototyping and tutoring.

I export it as a python script using the menu dropdown or nbconvert, i.e.

ipython nbconvert --to python notebook.ipynb

However, I would like to make notebook.py executable directly without having to hack it by hand each time, in order that I can keep updating notebook.ipynb and overwriting notebook.py with my changes. I also want to include command-line arguments in notebook.py. My boilerplate is, for example:

#!/usr/bin/env ipython
import sys
x=sys.argv[-1]

with chmod +x notebook.py of course.

One route could be to make these lines (be they python or command-line directives) ignorable in the jupyter/ipython notebook - is there a way to do this by e.g. detecting the jupyter/ipython environment?

Edit1: This is tantamount to saying:

How can I include lines in the notebook.ipynb that will be ignored in the notebook environment but parsed in notebook.py generated from it?

Edit2: This question is a partial answer, but doesn't tell me how to include the #!/usr/bin/env ipython line: How can I check if code is executed in the IPython notebook?

Edit3: Could be useful, but only if %%bash /usr/bin/env ipython would work - would it..? How do I provide inline input to an IPython (notebook) shell command?

Edit4: Another attempted answer (subtle): Since # is a comment in python, putting #!/usr/bin/env ipython in the first cell of the notebook means that it will be ignored in jupyter/ipython, but respected in the exported notebook.py. However, the #! directive is not at the top, but can easily be chopped off:

> more notebook.py 

# coding: utf-8

# In[1]:

#!/usr/bin/env ipython


# In[2]:

print 'Hello'


# In[ ]:
1 Answers
Related