Vim: use the selected line as input to python function

I am new to vim. I want to ensure that vim will return the output of the python function to a text file. The idea is that I select a piece of text and press F5 and get the output. The complication is that this function is part of the 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 a "valid range"

+4
source share
2 answers

The selected lines are passed to the stdin 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 part of the string:

 vnoremap <F5> d:let @a=system('python -c "import sys, Bio.Seq; sys.stdout.write(Bio.Seq.reverse_complement(\"' . @" . '\"))"')<CR>"aP 
  • d → delete the selected part. side effect: changing the contents of the register. "
  • @" : register contents " (contents cut)
  • . : A binary operator that concatenates strings.
  • let @a = system(..) : execute an external command and save its output in register a .
  • "aP: insert the contents of a into the register to the current cursor position.
+2
source

First of all, you will need ** to write your python parts so that the data is read from stdin and then output to stdout. Then you can apply your code in the following style:

 fun! DoMyPythonThing() range exec ":'<,'>! python ./path/to/your/script.py" endfun vnoremap <F3> :call DoMyPythonThing()<CR> 

Ex Team Idea:! lies in the fact that you give it an executable program, and vim passes the rendered text to it and replaces the area with the program output.

Notice the range in the function definition. Pay attention to the mapping, which we restrict only to visual mode displays. If you also like to wave your mouse, think about how to display in select mode.

**) Well, you can write in-vim python to accomplish this, but it's harder to check, and you went with the program's external route by calling ! anyway.

+1
source

Source: https://habr.com/ru/post/1490016/


All Articles