I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:
%
If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:
If you want to do something in randomly chosen places throughout your file, you're better of recording keystrokes and replaying them. Go to the first line you want to change, and hit qz
to starting recording into register z
. Do whatever edits you want for that line and hit q
again when you're finished. Go to the next line you want to change and press @z
to replay the macro.
You can execute the code, read the output on the cursor and finish with u
, supposing you are executing python code. Simple and quick.
:r !python %
u
I like it over mapping and selecting-in-visual-mode, like with too-much-php, because it keeps the base simple!
if you have written your python script in a new [No Name] buffer, then you can use following:
:0,$!python
when you have a no name buffer then you can not use '%', hence the need for 0,$ which means all lines in buffer starting with line zero until the last line
output will be written in buffer and unfortunately not at the end
Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given (., %, ...)."
One common use is to sort lines of text using the 'sort' command available in your shell. For example, you can sort the whole file using this command:
:%!sort
Or, you could sort just a few lines by selecting them in visual mode and then typing:
:!sort
You could sort lines 5-10 using this command:
:5,10!sort
You could write your own command-line script (presuming you know how to do that) which reverses lines of text. It works like this:
bash$ myreverse 'hello world!'
!dlrow olleh
You could apply it to one of your open files in vim in exactly the same way you used sort
:
:%!myreverse <- all lines in your file are reversed
In any of your vim windows, type something like this:
for x in range(1,10):
print '-> %d' % x
Visually select both of those lines (V to start visual mode), and type the following:
:!python
Because you pressed ':' in visual mode, that will end up looking like:
:'<,'>!python
Hit enter and the selection is replaced by the output of the print
statements. You could easily turn it into a mapping:
:vnoremap <f5> :!python<CR>
From your example, it appears as though you want to execute a Python script and have the output of the script appear in the current Vim buffer. If that's correct, then you can do the following at the command line in Vim:
%!python -c "for i in xrange(25): print 6*i"
The -c
option to python
gives it a script to run. However, you may find this technique useful only in very short cases, because unlike some other languages, Python does not lend itself well to writing complete programs all on one line.