How to define functions in ipython configuration file?

Using ipython 0.11 if I find a function definition, for example

def f(s): print s 

then I can use this function in this ipython session, but I do not know how to determine what is in the ipython_config.py file. If I just type the function definition in the file and try to use the it undefined function.

Any idea?

+4
source share
3 answers

There are two answers here:

Firstly, for super simple functions like above, you can define them in exec_lines , for example:

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

(you can define arbitrarily complex functions this way, but this is annoying in a couple of lines)

For more complex code, you can write a script that you want to run at startup and add it 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 that this is a little annoying, so at 0.12 there will be an autoload folder in the profile directories, and everything you enter there will be launched automatically. This essentially adds extra glob.glob('*.py') to exec_files (which you can do yourself in 0.11, of course).

+9
source

You 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 on the ipython configuration file can be found here: http://ipython.org/ipython-doc/dev/config/ipython.html

+2
source

Multi-line functions can be defined in the *.py and *.ipy in the startup directory in the profile directory.

(Note that *.ipy and *.py files are handled differently.)

The profile directory can be opened from the command line using

 $ ipython locate profile 
0
source

Source: https://habr.com/ru/post/1379928/


All Articles