I am quite newbie in vim. What I want to achieve is that vim will return the output of a python function in my text file. The idea is that I select a part of text and press F5 and get the output. The complication is that this function is part of a library and I have to import it. I tried this
command MyPythonFunction execute "!python from Bio.Seq import reverse_complement; reverse_complement(%)"
map <F5> :MyPythonFunction<CR>
and I get "no range allowed"
Selected lines are passed to stdin of the command. So read it using sys.stdin.read()
fun! ReverseComplement()
exec ":'<,'>! python -c \"import sys, Bio.Seq; print Bio.Seq.reverse_complement(sys.stdin.read().rstrip())\""
endfun
vnoremap <F5> :call ReverseComplement()<CR>
EDIT
pass a part of a line:
vnoremap <F5> d:let @a=system('python -c "import sys, Bio.Seq; sys.stdout.write(Bio.Seq.reverse_complement(\"' . @" . '\"))"')<CR>"aP
"
changed. @"
: content of register "
(cut contents) .
: binary operator that concatenate strings. let @a = system(..)
: Execute external command, and save its output to a
register. a
register before current cursor position. First of all, you are going to need** write your python parts in such a manner that the data is read from stdin and then output to stdout. You can then apply your code in following style:
fun! DoMyPythonThing() range
exec ":'<,'>! python ./path/to/your/script.py"
endfun
vnoremap <F3> :call DoMyPythonThing()<CR>
The idea behind ex's command :!
is that you give it an executable program, and vim pipes the visualized text to it and replaces the region with the ouput of the program.
Note the range
there in the function definition. Note about the mapping that we restrict ourselves in visual mode mappings only. If you like to wave the mouse as well, consider mapping in selection mode as well.
**) Well, it's possible to write in-vim python to perform this, but that's harder to test and you went with the external-program route by calling !
anyway.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.