IPython workflow (edit, run) - python

Is there a GUI for IPython that allows me to open/run/edit Python files? My way of working in IDLE is to have two windows open: the shell and a .py file. I edit the .py file, run it, and interact with the results in the shell.
Is it possible to use IPython like this? Or is there an alternative way of working?

When I'm working with python, I usually have two terminal windows open - one with IPython, and the other with a fairly customized Vim.
Two good resources:
http://blog.dispatched.ch/2009/05/24/vim-as-python-ide/
http://dancingpenguinsoflight.com/2009/02/python-and-vim-make-your-own-ide/
Though it sounds like what you want is IPython's magic function %ed/%edit:
An example of what you can do:
In [72]: %ed
IPython will make a temporary file named: c:\docume~1\wjwe312\locals~1\temp\ipython_edit_ar8veu.py
In the file I put:
x = "Hello World"
print 3
After saving and quitting the file:
Editing... done. Executing edited code...
3
Out[72]: "x = 'Hello world'\nprint 3\n"
In [73]: x
Out[73]: 'Hello world'
You can define functions or anything else - just remember that the contents of the file will be executed when you close it.
Another similar workflow is to cd to the directory containing your Python script that you're editing with your favorite editor. Then you can %run the script from within IPython and you'll have access to everything defined in the file. For instance, if you have the following in the file test.py in your /home/myself directory:
class Tester(object):
def __init__(self):
print "hi"
def knightme(name):
print "Hello, Sir ", name
Then you can do the following:
In [42]: cd /home/myself
/home/myself
In [43]: %run test.py # <Tab> autocomplete also works
In [44]: knightme('John')
Hello, Sir John
In [45]: t = Tester()
Hi
Either a mix or one of those workflows should give you something very similar to the way you're used to working in IDLE.

Spyder, previously known as SPyderlib / Spyder2
Pretty lightweight, fast and support almost all features you will ever need to work with a python project. It can edit and run .py files in an embedded IPython instance and then interact with them, set breakpoints, etc.
full-size

Try Spyder, I have spent all day trying to find an IDE which has the functionality of ipython and Spyder just kicks it out of the park..
Autocomplete is top notch right from install, no config files and all that crap, and it has an Ipython terminal in the corner for you to instantly run your code.
big thumbs up

Take a look at DreamPie. Might be what you are looking for.

Personally, I like PyScripter. Unfortunately, it only works on Windows, but also runs perfectly in Wine.

The latest version of IdleX supports IPython within IDLE, as well as the %edit magic. You can run your files from the IDLE editor within the IPython shell many ways, either by F5 (run everything), F9 (run a selection), or Ctrl+Enter (run a subcode).

sudo apt-get install ipython
Once you are done with installing ipython.
Start ipython from terminal (just hit ipython in the ternminal)
To run ravi.py file all you need to do is
%run ravi.py

If you like the work-flow under Matlab, then you probably should try the following two:
1, Try the combination of Spyder and Vim.
Edit python files in Vim (Spyder can reload the file automatically)
Run the code in Spyder (in the same interpreter, which is important for me):
Use F9 to run the current file
Ctrl+F9 to run the selected block
2, Use Vim + conque-shell. (on google code)
Open your preferred Python interpreter in Vim,
e.g., just :ConqueTermSplit python.
then visual select some Python code
press F9 to paste and run it in the Python interpreter buffer.
Note: a few more:
:ConqueTermVSplit python,
:ConqueTerm python
:ConqueTermVSplit rlwrap python
If your interpretor misses readline, you can use rlwrap.

You might like PySlices...
It's kind of a shell/editor hybrid that lets you save your session as special (barely) modified python files called .pyslice files.
It's now part of wxPython, so just install that (v2.8.11 or later) and run "python -m wx.py.PySlices" on the command line to launch it.
That said, I still end up using an external editor for scripts (geany).

I want to suggest excellent plugin for vim that makes two-way integration between Vim and IPython: vim-ipython.
From project page on http://github.com/ivanov/vim-ipython:
Using this plugin, you can send lines or whole files for IPython to execute, and also get back object introspection and word completions in Vim, like what you get with: object? and object. in IPython.
This plugin has one big limitation: it doesn't support python 3 (it's planned).

Personally, I use what #Wayne suggested, a combination of vim and ipython...
However, if you'd prefer a different approach, take a look at spyder.
As of the latest version (1.1) ipython should be fully integrated. If you download an earlier version, things will work fine with ipython as an external shell, but you won't get a few of spyder's nifty features (like viewing all of the currently defined variables in the workspace window).
Spyder is definitely a bit heavyweight, but it's an interesting project.
Another (very, very, new) similar project to take a look at is iep. It will (sort-of) work with ipython as shell, and I'd be willing to be bet that nicer ipython integration will be along before too long. At any rate, iep is essentially a more lightweight alternative to spyder.
Both of these are oriented towards scientific computing, and so have nice integration with things like matplotlib (and thus can automatically run gui main loops in a seperate thread). They're not quite like "normal" IDE's but they may fill the niche you're looking for quite nicely.

You can use the autoreload module in IPython to automatically reload code.
Open jupyter qtconsole or jupyter console and type:
%load_ext autoreload
%autoreload 2
from your_work_file import *
Now every time you save your_work_file.py, it will be automatically reloaded.
Hint: if you want this to happen automatically, put the followinglines in your ipython_config.py file:
c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']

Try Ptpython. It has much better integration with VIM. You can directly edit in VIM by just pressing V. It also allows browsing your history.. so you can pretty much code in the shell, and incrementally build up your code.
If you are already familiar with ipython, you can check the advantages of ptpython here:
https://www.youtube.com/watch?v=XDgIDslyAFM

I just use the exclamation mark (!) to run vi as a shell command
In [1]: !vi myScript.py
and when done with editing I just quit vi to get back to the Ipython shell.
To run the script one can then use
In [2]: %run myScript.py
as suggested in another answer and not !python ... because the Python version in ipython might be different from the one in the underlying shell.
If you want to dump some code in a file use the magic %%writefile
In [3]:%%writefile myScript.py
...: print("hello")
...:
...:
Be careful because this will overwrite myScript.py. To append use %%writefile -a.

Related

iPython automatically at launch in Visual Studio Code on Os X

I would like that iPython run automatically when I launch VSC instead of typing ipython and press enter in the terminal. The answer here How to set ipython/jupyter as the default python terminal for vscode? doesn't work as it is for windows but it shouldn't be really different. Also, is there something similar to the 'Execute' button in Spyder instead of typing %run filename ? Thanks !
I presume you mean you want to run the "Python Interactive Window" and not just an iPython console on startup
There is currently no way to run it on startup. At least no way without writing another extension that would run a command when opening a workspace. It would be simple for us to add one though. Probably a workspace setting. Can you log an issue here:
https://github.com/Microsoft/vscode-python/issues/new
For you second question, 'Execute' in spyder, we have 'Run Current File in Python Interactive Window'. This works on any python file. You can get to it through the context menu on a file or through the command palette.
Sadly the nice workflow of spyder is not provided by any official extension at the moment (as far as I know).
But you can implement the basics easily on your own by writing an extension. Even with no experience in TypeScript you can quickly build an extension which starts an IPython console as soon as you open a python file. I also managed to execute a startup script which implements the runfile method. VS Code also allows keybindings for your functions, so that you can almost work like you can with spyder.
Spyder modified the IPython terminal quite a bit though, so it won't feel exactly the same. But after all, everything there is open source so you could implement it yourself, which is what I'm trying to do in my free time.

How to save code at the python prompt in the terminal to a local file

I have just written a bunch of lines of code on the Python prompt at the terminal. Now, I want to save all those lines of code to a .py file.
I am unable to find out how to do that. The only thing that I could find on StackOverflow was this answer but it shows only how to do it in an iPython notebook. I am not using an iPython notebook. I am running the code at the command line on the terminal.
I tried to follow that answer (because just in case) and ran the %save magic command on the terminal but it gave a SyntaxError.
So, how do save it?
Thanks!
See http://blog.e-shell.org/174 . As wu explains, the python prompt is using readline, and you can import a Python library to access this.
>>> import readline
>>> readline.write_history_file('/path/to/history.txt')
You can trying using another interpreter : bpython , I belive it has what you need,check it out.
Save the code you've entered to a file.
You seem to be affected by the misconception, that the python environment is workspace-centered (similar to what I know from Smalltalk and some LISP variants):
fire up with an initial workspace
modify by your liking
store the result
This is unfortunately not the case. While you can import existing files, the other option is to specify an existing file as initially to be loaded and keep the interpreter open by using the -i option.
It really depends on your terminal for the exact commands.
The general idea is to copy everything (if possible) or one page at a time from the terminal into a text editor and then clean the >>> prompts (and possibly other formatting problems) in the text editor.
But anyway, typing a lot of commands directly in the execution environment if really bad practice. At least you test a handful of lines and immediately save them in a file. IDLE is great at this game...

What's the best practice in the workflow of writing and running python files with Vim?

Currently, I write pythons files in Vim, and run it with jupyter qtconsole. The advantage of this way is that I could work with Vim so get all the benefits of Vim.
I could run the python directly in Vim using the pymode plugins, but in this way I cannot see and manipulate the output variables, and the figures are opened in another window which is quite annoying when I have to close them to make Vim responsible again. Compared with this, in jupyter qtconsole I could use %maplotlib inline to display figures elegantly.
However, my current workflow has a big disadvantage that every time I run my python script in qtconsole, and then I edit my python script, it is not so easy to run it again with the modified script. Since the module has been loaded, rerun it will not automatically reload the modified module source. I found no easy way to overcome this drawback. Currently I have to restart the kernel and then reset the path, turn on %matplotlib inline, and %run python-script.py again.
Any one can give me a solution?
I find an answer which solves my problem by using ipython extension autoreload.
%load_ext autoreload
%autoreload 2
Then I do not have to restart kernel any more.

notepad++ run selected code in python console seamlessly

I often use R to analyze data, and really enjoy Notepad++ along with NppToR. Especially, NppToR enables to run a part of code without much hassle. I just highlight a snippet of R code to run and press F8. Then the code magically runs in R console.
Now, I am required to use python to analyze data. I know that ipython is great to work interactively, but it is always very annoying to copy a snippet of python code and manually paste that into ipython console. Also, indentation is often mixed and thus the entire lines are failed to run. Note that I want to run 'selected' lines of codes, not the entire file.
So I am looking for a program/plugin/macro similar to NppToR, but working with python/ipython console. I have searched the web, but couldn't find such one. Some plugins are nice, but not exactly what I want. For example, Python Script enables extending Notepad++ itself, but not outside. Various other 'Run' extensions enables the entire file to be run in python.
You can customize the editor IPython uses for the edit command, and configure IPython to use Notepad++. IPython 0.11 creates a .ipython/profile_default folder in your user folder (in my case C:/Users/zk/.ipython/profile_default). To configure IPython to use Notepad++ create .ipython/profile_default/ipython_config.py with the following:
c = get_config()
# use DOS style path, C:/PROGRA~2 on my 64-bit system points to C:/Program Files (x86)
c.TerminalInteractiveShell.editor = 'C:\PROGRA~2\NOTEPA~1\NOTEPA~1.exe'
# set editor for Qt Console, if you wish to use that
c.IPythonWidget.editor = 'C:\PROGRA~2\NOTEPA~1\NOTEPA~1.exe'
You can then start up IPython and use the edit command to run Notepad++ from IPython, saving and closing Notepad++ will execute the file in IPython.
If you don't mind installing PyQt4 and pyzmq (and I believe pygments, at least for IPython 0.12-dev), IPython's Qt console works really well (frankly the nicest interactive environment you can get for Python). You can paste directly into IPython and it'll adjust indentation for you (shifting over padded code).

Advice regarding IPython + MacVim Workflow

I've just found IPython and I can report that I'm in deep love. And the affection was immediate. I think this affair will turn into something lasting, like the one I have with screen. Ipython and screen happen to be the best of friends too so it's a triangular drama. Purely platonic, mind you.
The reason IPython hits the soft spots with me are very much because I generally like command prompts, and especially *nix-inspired prompts with inspiration from ksh, csh (yes, chs is a monster, but as a prompt it sport lots of really good features), bash and zsh. And IPython does sure feel like home for a *nix prompt rider. Mixing the system shell and python is also a really good idea. Plus, of course, IPython helps a lot when solving the Python Challenge riddles. Invaluable even.
Now, I love Vim too. Since I learnt vi back in the days there's no turning back. And I'm on Mac when I have a choice. Now I'd like to glue together my IPython + MacVim workflow. What I've done so far is that I start Ipython using:
ipython -e "open -a MacVim"
Thus when I edit from IPython it starts MacVim with the file/module loaded. Could look a bit like so:
In [4]: %run foo #This also "imports" foo anew
hello world
In [5]: edit foo
Editing... done. Executing edited code... #This happens immediately
hello world
In [6]: %run foo
hello SO World
OK. I think this can be improved. Maybe there's a way to tie IPython into MacVim too? Please share your experiences. Of course if you use TextMate or some other fav editor I'm interested too. Maybe some of the lessons are general.
I use Linux, but I believe this tip can be used in OS X too. I use GNU Screen to send IPython commands from Vim as recommended by this tip. This is how I do it:
First, you should open a terminal and start a screen session called 'ipython' or whatever you want, and then start IPython:
$ screen -S ipython
$ ipython
Then you should put this in your .vimrc:
autocmd FileType python map F5 :w<CR>:!screen -x ipython -X stuff $'\%run %:p:h\n'<CR><CR>
Then when you hit F5, it will tell Screen to execute the command '%run file' inside the 'ipython' created previously, where file is your current buffer in Vim.
You can tweak this to execute the command you want inside IPython from Vim. For example I use this:
autocmd FileType python map <F5> :w<CR>:!screen -x ipython -X stuff $'\%reset\ny\n\%cd %:p:h\n\%run %:t\n'<CR><CR>
This executes %reset (answering yes to the prompt), then change to the directory where the current buffer in vim is located and then %run the file. This is specially useful if you have the %pdb active in IPython.
Don't forget that you need an active Screen session called 'ipython' with IPython running inside.
If you like Emacs. There is good support for IPython.
This questions is stale now, but just for reference - if you're using IPython 0.11 with ZeroMQ enabled, take a look at vim-ipython (an older version of which shipped with 0.11).
Using this plugin, you can send lines or whole files for IPython to execute, and also get back object introspection and word completions
in Vim, like what you get with: object?<enter> and object.<tab> in IPython.
Take a look at two screencasts of this plugin in action on this post.
In the ipythonrc.ini file in you home directory change the editor to MacVim.
I've had the same issue. After experimenting this is my solution: if you placed MacVim.app in /Applications and mvim is in your path, in ~/.ipython/ipythonrc change the line
editor 0
to
editor mvim --remote-tab-wait-silent
I think you need to keep MacVim open in the background. You could also use the -f flag. Look at this thread from the MacVim google group.

Categories

Resources