Execute a python command within vim and getting the output


Question

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.

1
5
8/31/2010 12:41:10 PM

Accepted Answer

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.

2
9/1/2010 12:00:54 PM

:,!python -c "import os; print os.listdir('aDirectory')[0]"

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon