Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a python command within vim and getting the output

Tags:

python

vim

When Vim is compiled with Python support, you can script Vim with Python using the :python command. How would I go about using this to execute the command and insert the result under the cursor? For example, if I were to execute :python import os; os.listdir('aDirectory')[0], I would want the first filename returned to be inserted under the cursor.

EDIT: To clarify, I want the same effect as going to the terminal, executing the command, copying the result and executing "+p.

like image 291
Chinmay Kanchi Avatar asked Aug 31 '10 11:08

Chinmay Kanchi


2 Answers

:,!python -c "import os; print os.listdir('aDirectory')[0]"
like image 138
mg. Avatar answered Oct 13 '22 22:10

mg.


The following works fine for me: write the python code you want to execute in the line you want.

import os
print(os.listdir('.'))

after that visually select the lines you want to execute in python

:'<,'>!python

and after that the python code will replaced by the python output.

like image 36
skeept Avatar answered Oct 13 '22 23:10

skeept