Small issue when running Python code straight from VIM

Viewed 39

I want to be able to set up the hot key \\ to be able to write and run python script from VIM without each time having to type in

:w
:! python3 file.py

What I have done so far is pasted the following into my vimrc file:

"{{{ The following is for sourcing command.vim whenever exists.
" Function to source only if the file command.vim exists
" https://devel.tech/snippets/n/vIIMz8vZ/load-vim-source-files-only-if-they-exist
"
function! SourceIfExists(file)
  if filereadable(expand(a:file))
    echom a:file . " is about to be sourced."
    exe 'source' a:file
  endif
endfunction
autocmd BufEnter * call SourceIfExists("command.vim")
" }}}

and then in the same directory that my python file is, I create a file named command.vim and paste the following inside that file:

noremap <leader><leader> :w <cr> :!python3 % &<cr>

Now this almost works perfectly except for the following issue. Suppose I want to run the following script, which I'll call file.py:

import numpy as np

x = np.linspace(0, 5, 6)
y = np.linspace(6, 10, 5)

print('{}\n{}'.format(x, y))

If I run this the standard way by using :! python3 file.py then the output is the following:

[0. 1. 2. 3. 4. 5.]
[ 6.  7.  8.  9. 10.]

Press ENTER or type command to continue

But, if I use the \\ method to run the same script, I get the following output:

Press ENTER or type command to continue[0. 1. 2. 3. 4. 5.]
                                                          [ 6.  7.  8.  9. 10.]

and you can see that the output of the script using \\ is not formatted nicely like it is when using the standard command :! python3 file.py.

Anyone know how to fix this?

1 Answers

What your mapping does:

:w
:!python3 % &

is different from what you do manually:

:w
:!python3 file.py

If you want the same outcome as the manual way, you will simply have to do the same thing:

nnoremap <leader><leader> :w<cr>:!python3 %<cr>

It is the unnecessary & that is causing your problem: it sends the command to the background, so Vim thinks it is finished and it takes back control of the terminal. But the background job still prints its output to the same terminal as Vim and you get a mess. Removing that & will fix your mapping.


By the way, the whole command.vim thing is a) useless, b) over-complicated, and b) a red herring. You should remove it from the question… and from your vimrc.

Related