Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define functions in ipython configuration file?

Tags:

python

ipython

Using ipython 0.11 if I type a function definition, like

def f(s): print s

then I can use that function in that ipython session, but I don't know how to define that in the ipython_config.py file. If I just type the function definition in the file and try to use the function it it undefined.

Any idea?

like image 801
skeept Avatar asked Dec 28 '22 11:12

skeept


2 Answers

Two answers here:

First, for super simple functions like the one above, you can define them in exec_lines, e.g.:

c.InteractiveShellApp.exec_lines = [ "def f(s): print s" ]

(you can define arbitrarily complex functions this way, but it gets annoying beyond a couple of lines)

For more complicated code, you can write a script that you would like to run at startup, and add that to the exec_files list:

c.InteractiveShellApp.exec_files = [ "/path/to/myscript.py" ] 
# if you put the script in the profile dir, just the filename will suffice

We realized this is slightly annoying, so in 0.12, there will be a startup folder in profile directories, and anything you put in there will be run automatically. This is essentially adding an extra glob.glob('*.py') to exec_files (which you can do yourself in 0.11, of course).

like image 61
minrk Avatar answered Jan 17 '23 10:01

minrk


You'll need to define a python file to run when ipython starts. You can do this by setting the exec_files list:

c = get_config()
c.InteractiveShellApp.exec_files = [
        '/tmp/mymodule.py'
]

Then my file "/tmp/mymodule.py":

def foo():
    print "bar"

And finally, using this:

$ ipython

In [1]: foo()
bar

More information about the ipython config-file can be found here: http://ipython.org/ipython-doc/dev/config/ipython.html

like image 37
Adam Wagner Avatar answered Jan 17 '23 11:01

Adam Wagner