How to set default path automatically in IPython - python

I'm using WingIDE for development and Ipython for running my scripts. I'm facing some inconvenience on several points:
Whenever I update my code, I have to reload my module in order to update it in IPython. To solve that I followed Jomonsugi's answer in the following link: How to automatically reload modules in IPython?
and it works.
Each time I launch IPython, my path is set to my exe's location and I have to cd to my script's directory.
I tried to change directory automatically when launching IPython by setting the parameter c.InteractiveShell.ipython_dir = <mypath> in ipython_config.py but it doesn't work.
Is it possible to set the default path? Is there a particular parameter to set in ipython_config.py?

One way is to use your startup.py file. It should be located somewhere like:
C:/Users/yourname/.ipython/profile_default
If it's not there already, create it. Then use
import os
os.chdir('C:/Users/mypath')
Those two lines will then be run at IPython startup.
Source: IPython.org > Startup Files

I’m sure Brad Solomon’s answer is right for his version of IPython, but I’ve just downloaded IPython with pip install ipython and my startup files are in a directory nested one deeper than his. My IPython version is 7.18.1, and the start-up files are located in ~/.ipython/profile_default/startup/. There is a README there which states
This is the IPython startup directory
.py and .ipy files in this directory will be run *prior* to any code
or files specified via the exec_lines or exec_files configurables
whenever you load this profile.
Files will be run in lexicographical order, so you can control the
execution order of files with a prefix, e.g.::
00-first.py
50-middle.py
99-last.ipy
That’s pretty self-descriptive, but I would add to this (for anyone coming here from here) that %load_ext autoreload is an IPython command, so you might want to create a file startup.ipy with contents something like this:
%load_ext autoreload
%autoreload 2
print('IPython startup file - created 2020/9/28')

Related

Disable Jedi - no ipython_config.py?

I have Anaconda distribution of Python on Windows.
I have issues with auto-complete in Jupyter Notebook.
I think auto-complete was working before but it doesn't quite work now. I don't get it.
So I am trying to disable Jedi as it messes up my auto-complete in Jupyter Notebook (that's what other folks say who had the same issue).
This is described on several web pages as a possible solution.
See also
Kernel taking too long to autocomplete (tab) in Jupyter notebook
I follow this suggestion
https://github.com/ipython/ipython/issues/10493#issuecomment-298968328
I can locate my profile directory but there's no ipython_config.py there.
C:\Users\username\.ipython> dir ipython_config.py /s
Volume in drive C is OS
Volume Serial Number is BC61-492E
File Not Found
C:\Users\username\.ipython>
Why so? What am I missing?
Should I create the file myself if it's missing?
Maybe under the profile_default subfolder of C:\Users\username\.ipython?
Just in case you need it on the fly for a single notebook in jupyter:
%config IPCompleter.use_jedi=False
does the magic trick, too.
If the file ipython_config.py is missing then:
Run ipython profile create in the profile_default sub-folder
Append this property c.IPCompleter.use_jedi = False
to the newly created ipython_config.py file

Where can I put a startup script in Jupyter?

I'm looking for a way to put my startup script in Jupyter. In IPython, I put it under the $IPYTHON_DIR/profile_default/startup/.
In Jupyter, it seems that the config file should be $JUPYTER_CONFIG_DIR/jupyter_notebook_config.py. However, I would like to use my startup file, which import a slew of Python libraries at the launch of the kernel.
Where can I put such file in Jupyter?
You can get the default startup script folder via this in jupyter notebook:
get_ipython().profile_dir.startup_dir
On my Windows PC, the folder is: C:\Users\myusername\.ipython\profile_default\startup
And do read the README file under the folder.
Files will be run in lexicographical order, so you can control
the execution order of files with a prefix, e.g.::
00-first.py
50-middle.py
99-last.ipy
So you can put a file named 00-xx.py under the folder.

Load iPython with custom packages imported

Does anyone know if it is possible to load ipython preloaded with custom packages please?
I'm running Python 2.7 on Windows 8.
When I load a DOS prompt, I run ipython preloaded with pylab by typing
ipython --pylab
I've managed to create a shortcut to open a DOS prompt with this automatically fired, thus effectively creating a shortcut to iPython.
However, I'd like iPython to start preloaded with some of my custom packages. So I wonder if there is a way to start iPython and automatically execute the following lines, say:
import package1 as my_package
import package2 as my_second_package
I've had a look online and there's some information on "magic" commands and scripts in iPython which looks like it might help, although I wasn't sure how to use this.
All guidance welcomed.
Many thanks.
What you want is a startup script.
First run ipython locate profile to find the profile folder. Then find a startup folder in there. Create a .py file (any name) in the startup folder with the imports you want, and IPython will run that whenever you it starts.
If you have a look at the documentation, you will find out that IPython will run whatever is inside the file pointed by the PYTHONSTARTUP variable.
Create one, export the variable, and there you go.
References:
http://ipython.org/ipython-doc/stable/interactive/reference.html#ipython-as-your-default-python-environment
https://docs.python.org/2/using/cmdline.html#envvar-PYTHONSTARTUP

Add a directory to Python sys.path so that it's included each time I use Python

Currently, when trying to reference some library code, I'm doing this at the top of my python file:
import sys
sys.path.append('''C:\code\my-library''')
from my-library import my-library
Then, my-library will be part of sys.path for as long as the session is active. If I start a new file, I have to remember to include sys.path.append again.
I feel like there must be a much better way of doing this. How can I make my-library available to every python script on my windows machine without having to use sys.path.append each time?
Simply add this path to your PYTHONPATH environment variable. To do this, go to Control Panel / System / Advanced / Environment variable, and in the "User variables" sections, check if you already have PYTHONPATH. If yes, select it and click "Edit", if not, click "New" to add it.
Paths in PYTHONPATH should be separated with ";".
You should use
os.path.join
to make your code more reliable.
You have already used __my-library__ in the path. So don't use it the second time in import.
If you have a directory structure like this
C:\code\my-library\lib.py and a function in there, e.g.:
def main():
print("Hello, world")
then your resulting code should be
import sys
sys.path.append(os.path.join('C:/', 'code', 'my-library'))
from lib import main
If this is a library that you use throughout your code, you should install it as such. Package it up properly, and either install it in your site-packages directory - or, if it's specific to certain projects, use virtualenv and install it just within the relevant virtualenvs.
To do such a thing, you'll have to use a sitecustomize.py (or usercustomize.py) file where you'll do your sys.path modifications (source python docs).
Create the sitecustomize.py file into the \Lib\site-packages directory of your python installation, and it will be imported each time a python interpreter is launched.
If you are doing this interactively, the best thing to do would be to install ipython and configure your startup settings to include that code. If you intend to have it be part of a script you run from the interpreter, the same thing applies, since it will have access to your namespace.
On the other hand, a stand alone script should not include that automatically. In the future, you or some other maintainer will come along, and all the code should be obvious, and not dependent upon a specific machine setup. The best thing to do would be to set up a skeleton file for new projects that includes all of the basic functionality you need. That, along with oft-used snippets will handle the problem.
All of your code to run the script, will be in the script, and you won't have to think about adding that code every time.
Using jupyter with multiple environments, adding the path to .bashrc didn't work. I had to edit the kernel.json file for that particular kernel and append it to the PYTHONPATH in env section.
This only worked in that kernel but maybe this can help someone else.

How can I start IPython running a script?

My use case is I want to initialize some functions in a file and then start up IPython with those functions defined. Is there a way to do something like this?
ipython --run_script=myscript.py
In recent versions of IPython, you do need to add the -i option to get into the interactive environment afterwards. Without the -i it just runs the code in myfile.py and returns to the prompt.
ipython -i myfile.py
Per the docs, it's trivial:
You start IPython with the command:
$ ipython [options] files
If invoked with no options, it
executes all the files listed in
sequence and drops you into the
interpreter while still acknowledging
any options you may have set in your
ipythonrc file. This behavior is
different from standard Python, which
when called as python -i will only
execute one file and ignore your
configuration setup.
So, just use ipython myfile.py... and there you are!-)
You can use IPython profiles to define startup scripts that will run every time you start IPython. A full description of profiles, is given here. You can create multiple profiles with different startup files.
Assuming you only need one profile, and always want the same startup files every time you start IPython, you can simply modify the default profile. To do this, first find out where your IPython configuration directory is in an ipython session.:
In [1]: import IPython
In [2]: IPython.paths.get_ipython_dir() # As of IPython v4.0
In [3]: print(ipython_config_dir)
/home/johndoe/.config/ipython
For this example, I am using Ubuntu Linux, and the configuration directory is in /home/johndoe/.config/ipython, where johndoe is the username.
The default_profile is in the profile_default subdirectory. Put any starting scripts in profile_default/startup. In the example here, the full path would be /home/johndoe/.config/ipython/profile_default/startup.
Nowadays, you can use the startup folder of IPython, which is located in your home directory (C:\users\[username]\.ipython on Windows). Go into the default profile and you'll see a startup folder with a README file. Just put any Python scripts in there, or if you want IPython commands, put them in a file with an .ipy extension.
You seem to be looking for IPython's %run magic command.
By typing in IPython:
%run hello_world.py
you'll run the hello.py program saved in your home directory. The functions and variables defined in that script will be accessible to you too.
The following is for the case when you want your startup scripts to automatically be run whenever you use IPython (instead of having a script that you must specify each time you run IPython).
For recent versions (i.e., 5.1.0) of IPython, place one or more python scripts you wish to have executed in the IPYTHON_CONFIG_DIR/profile_PROFILENAME/startup folder.
On Linux, for example, you could put your Python startup code into a file named ~/.ipython/profile_default/startup/10-mystartupstuff.py if you want it to run when no IPython profile is specified.
Information on creating and using IPython profiles is available here.
Update to Caleb's answer for Python 3.5 in Ubuntu 14.04 (Trusty Tahr): I made this answer self-contained by copying relevant parts of Caleb's answer.
You can use IPython profiles to define startup scripts that will run every time you start IPython. A full description of profiles, is given here. You can create multiple profiles with different startup files.
Assuming you only need one profile, and always want the same startup files every time you start IPython, you can simply modify the default profile. To do this, first find out where your IPython configuration directory is in an IPython session:
Input:
import IPython
ipython_config_dir = IPython.paths.get_ipython_dir()
print(ipython_cofig_dir)
Output:
/home/johndoe/.ipython
For this example, johndoe is the username.
Inside the /.ipython folder, the default_profile is in the profile_default subdirectory. Put any starting scripts in profile_default/startup. In the example here, the full path would be
/home/johndoe/.ipython/profile_default/startup

Categories