As said above, we can run ipython scripts using ipython from command line:
ipython my_script.ipy
However, magic cells are currently not working well. For instance, if you have the following script:
%%writefile hello.txt
this is a line
another line
print ('hello')
my_path = '/path/to/folder'
list_of_txt = !ls {my_path}/*.txt
print (list_of_txt)
It will run the initial cell magic %%writefile
as if the whole file was a single cell. In order to avoid that, you have to use get_ipython().run_cell_magic ()
Since each ipython command needs a different function, I find it helpful to write ipython commands you want in a notebook, and then in the notebook's menu do File > "Save and Export Notebook As" > "Executable Script"
(in jupyter lab, but probably something similar can be done in plain jupyter notebook). It will convert all the ipython-specific code using appropriate functions from the IPython library.
For example, if we copy and paste the previous script in different cells of a notebook and export it as a .py file, it gives us the following python code:
code written in exported script:
get_ipython().run_cell_magic('writefile', 'hello.txt', 'this is a line\nanother line\n')
my_path = '/path/to/folder'
list_of_txt = get_ipython().getoutput('ls {my_path}/*.txt')
print (list_of_txt)
You can run the exported script directly using ipython from command line:
ipython my_exported_script.py
Or, inside an ipython
session, using
%run my_exported_script.py
This works for IPython 1.x