title: Convert ipython notebook to directly-executable python script
body: <p>I have a <code>jupyter/ipython</code> notebook that I am using for prototyping and tutoring.</p>
  
  <p>I export it as a python script using the menu dropdown or <code>nbconvert</code>, i.e.</p>
  
  <pre><code>ipython nbconvert --to python notebook.ipynb
  </code></pre>
  
  <p>However, I would like to make <code>notebook.py</code> executable directly without having to hack it by hand each time, in order that I can keep updating <code>notebook.ipynb</code> and overwriting <code>notebook.py</code> with my changes. I also want to include command-line arguments in <code>notebook.py</code>. My boilerplate is, for example:</p>
  
  <pre><code>#!/usr/bin/env ipython
  import sys
  x=sys.argv[-1]
  </code></pre>
  
  <p>with <code>chmod +x notebook.py</code> of course.</p>
  
  <p>One route could be to make these lines (be they python or command-line directives) ignorable in the <code>jupyter/ipython</code> notebook - is there a way to do this by e.g. detecting the <code>jupyter/ipython</code> environment?</p>
  
  <p><strong>Edit1:</strong> This is tantamount to saying:</p>
  
  <p>How can I include lines in the <code>notebook.ipynb</code> that will be ignored in the notebook environment but parsed in <code>notebook.py</code> generated from it?</p>
  
  <p><strong>Edit2:</strong> This question is a partial answer, but doesn't tell me how to include the <code>#!/usr/bin/env ipython</code> line: <a href="https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook">How can I check if code is executed in the IPython notebook?</a></p>
  
  <p><strong>Edit3:</strong> Could be useful, but only if <code>%%bash /usr/bin/env ipython</code> would work - would it..? <a href="https://stackoverflow.com/questions/37253817/how-do-i-provide-inline-input-to-an-ipython-notebook-shell-command">How do I provide inline input to an IPython (notebook) shell command?</a></p>
  
  <p><strong>Edit4:</strong> Another attempted answer (subtle): Since <code>#</code> is a comment in python, putting <code>#!/usr/bin/env ipython</code> in the first cell of the notebook means that it will be ignored in <code>jupyter/ipython</code>, but respected in the exported <code>notebook.py</code>. However, the <code>#!</code> directive is not at the top, but can easily be chopped off:</p>
  
  <pre><code>&gt; more notebook.py 
  
  # coding: utf-8
  
  # In[1]:
  
  #!/usr/bin/env ipython
  
  
  # In[2]:
  
  print 'Hello'
  
  
  # In[ ]:
  </code></pre>