How can I start IPython running a script? - python

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

Related

Is there a way to always execute a script when python starts? (similar site.profile in R)

In the R programming language, there is a site.profile file that defines some code that R processes execute on start up. Is there similar functionality in Python?
Edit: to clarify, this script should be executed if the user calls python from the command line, but also if python is spawned from another process (e.g. if the user's script uses subprocess to spawn another python).
If you only want this for interactive sessions (as opposed to also happening every time you run a script with python myscript.py or ./myscript or a module with python -m mymodule), what you want is the environment variable PYTHONSTARTUP:
If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session…
If you want this to always happen forever, of course, you need to set this environment variable in some appropriate global place—e.g., your shell profile on most *nix platforms, or both your shell profile and your launchd profile on macOS, or the appropriate part of the Control Panel on Windows (the appropriate part changes with almost every new version of Windows, but it usually has "System" in the name).
If you want this to happen for all users, not just the current user… the details for how to set a system-wide environment variable are more platform-specific, but otherwise the idea is the same.
If you want this to happen for every Python session, even when some other program is running a Python script and you didn't even know it was doing that… what you want is either usercustomize or sitecustomize, as documented in the site documentation:
This module is automatically imported during initialization. The automatic import can be suppressed using the interpreter’s -S option.
…
After these path manipulations, an attempt is made to import a module named sitecustomize, which can perform arbitrary site-specific customizations. It is typically created by a system administrator in the site-packages directory.
After this, an attempt is made to import a module named usercustomize, which can perform arbitrary user-specific customizations, if ENABLE_USER_SITE is true. This file is intended to be created in the user site-packages directory (see below), which is part of sys.path unless disabled by -s…
So, you want to find an appropriate place to override this. First try this:
python3 -m site
Then, if this didn't give you sys.path (probably only on pretty old Python, but just in case…), also do this:
python3 -c 'import sys; print('\n'.join(sys.path))'
If you want this customization to happen only for the current user, you want to create a usercustomize.py file in the USER_SITE directory listed by python3 -m site. If the directory doesn't exist, create it.
If you want it to happen for all users, you want a sitecustomize.py file in one of the sys.path directories. The problem is that there may already be one. For example, most linux distros' builtin Python packages have their own sitecustomize modules. If there is, python3 -c 'import sitecustomize; print(sitecustomize.__file__) will tell you where it is. Then, you can edit, or you can copy it, edit that copy, and place that copy somewhere that comes earlier in sys.path than the original. As a general rule, /usr/local is probably better than /usr, and site-packages is probably better than dist-packages is probably better than anything else.
The Python mechanism is called... site. It is a module that is automatically imported and sets up your environment. If it finds modules sitecustomize.py and usercustomize.py, it will import them as well. So these two are where you would put site-wide and personal customizations that you want to be a permanent part of your Python environment. See the site documentation for more details.
File pointed by your environmental variable PYTHONSTARTUP would be run on starting an interactive python session
And USER_SITE/usercustomize.py will be run for non-interactive python session.
Run python -c "import site; print(site.USER_SITE)" to find the USER_SITE dir location

How to set default path automatically in IPython

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')

When using Python Windows Launcher, is there any way to prevent having to type full path?

In Windows 8, I often use the Python Windows Launcher like
py C:/long/long/long/long/long/path/to/prog.py ...
Is there any way to set some environment setting, such as PATH or PYTHONPATH etc, to prevent having to type the full path to prog.py?
From my basic knowledge/research, PATH only helps with the py part of the command line and PYTHONPATH only helps with imports within prog.py, so how do I deal with the path to prog.py itself??
Notes:
I cannot modify the code, not even the "shebang" line, since it is needed to work on other platforms.
I cannot cd to the directory containing the programs to run them, because the programs will do something based on the directory they're run in (they'll modify the files in the directory they're run in).
I know that if I associate .py extension with the Python Windows Launcher, then I can run prog.py as the first item in the command line, and thus use PATH, but currently my .py extension is associated with my favorite editor and I'd like to keep it that way if possible (so I can double-click any Python file in Windows Explorer and edit it).
However, if someone suggests a solution where I can have a different association for Windows Explorer versus the command line, then that could be a potential solution! (i.e. in Windows Explorer, .py opens with the editor, while on command line, .py runs with Python Windows Launcher)
Add your long path to PYTHONPATH, then invoke your program as such:
python -m prog
Python will search for a module called prog and then run it as the main module.
Answer to my own question: Actually, I'm so silly. I could just set a variable for each program path (there are only a few programs paths), i.e.. prog=C:/long/path/to/prog.py and then do py %prog% .... I guess I figured out an answer to my own question that was acceptable to me.
Update: I just found something even better. I can do
doskey prog=py C:/long/path/to/prog.py $*
and then simply prog ... afterward
Now I just have to do some crazy stuff to get the doskey command into a file that will be run every time I start a console, as described here: https://stackoverflow.com/a/21040825/5182136

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

Running Python in CMD not working

I am a Python beginner and I am having trouble running Python from CMD. I have added the Python installation directory as a PATH variable (;C:\Python27). I am able to run the Python Interpreter from CMD, however when I issue a command like "python file.py command" from CMD, it returns "Error2, Python can't open, no such file/directory".
So what I do is go to "cd C:\Folder\Folder2\My_Python_Files", then type the "file.py command" each and every time. Is there faster or more efficient way of doing this? I am currently running Python2.7 on Windows 8.
When you run python <script>, it requires an actual path to the script being provided. You cannot specify "file.py" alone, unless it is right there in your current directory.
In windows, here are two steps you can take:
Associate .py files with python. Then you can run them directly without the python command as: /path/to/file.py
(right click a .py -> properties -> change to associate with python.exe)
Further step: Add a location to your PATH environment which will contain your python scripts. From there, you can just do file.py and it will be found in your search path.
So you could add C:\Folder\Folder2\My_Python_Files to your PATH and that is where you can store your executable python scripts.
Also you can set the PATH variable temporarily during a shell session:
SET PATH=%PATH%;C:\path\to\project
Just like PATH environment variable lists several directories for the system to search for executables, the PYTHONPATH do the same for Python to search for .py files. If you want scripts in a folder to be globally accessible (i.e. you can reference them by name just like you want, or you can import them from other scripts), add that folder to PYTHONPATH (create it if it doesn't exist).
Note that the command to invoke a script that is in your PYTHONPATH is:
python -m file [<script arguments>]
(i.e. use the -m option to treat it as a module, and don't use the extension .py)
Here's an article explaining in more detail how Python finds its source files (both in the command line and through import).
Note that you can also refer to the script by using its full path:
python C:\Folder\Folder2\My_Python_Files\file.py command
But by doing this, other files in the same folder that this script might reference through import might not work (since Python doesn't know where to search for them).
Unless the project's folder is in the PATH, you cannot call the file unless you are inside the project's folder. Don't create PATHs for projects, unless they are needed; it's unnecessary.
Just transverse to the file's directory and run the command inside the directory. That will work.
If the project will be used by other projects/files, you can use PYTHONPATH to set the directory, so the other projects can successfully access it.
Hope that helps.

Categories