I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a module having IPython code and include it in another IPython scripts?
You should not be saving the IPython extension stuff (?
, !
, %run
) in files. Ever. Those are interactive tools and they are something you type with your hands but never save to a file.
Find the common features among your files. You have exactly four kinds of things that are candidates for this.
Imports (
import
)Function definitions (
def
)Class definitions (
class
)Global variable assignments
You must remove all IPython interactive features from this code. All of it.
Rewrite your scripts so they (1) import your common stuff, (2) do the useful work they're supposed to do.
You must remove all IPython interactive features from this code. All of it.
Now you can run your scripts and they're do their work like proper Python scripts are supposed.
You can still use IPython extension features like !
, ?
and %run
when you're typing, but you should not save these into files.
Have you had a look at the IPython module (pydoc IPython
)? maybe you can access IPython's utilities through pure Python code.
technically if you save a script with the .ipy
extension, ipython will see that and use all it's fancy stuff rather than passing directly to the python interpreter. however, i would generally recommend against this, and go the route of S.Lott above.
If you enter the commands into an interactive version of IPython and then use the hist command (with -n to remove line numbers), IPython spits out all of the commands that you ran, with the actual python code used in place of !cd !ls, etc. Here's an example.
_ip.system("ls")
_ip.system("ls -F ")
_ip.magic("cd ")
http://ipython.scipy.org/moin/IpythonExtensionApi explains this object. This is basically what you need to do (adapted from the link):
import IPython.ipapi
_ip = IPython.ipapi.get()
Now all of the code you pasted from the IPython shell's hist command should work fine.