Is it possible to combine the two commands

map <F5> :w<CR>:exec '!python' shellescape(@%, 1)<CR>
map <F6> :w<CR>:exec '!poetry run'<CR>

so that when I press F5, it first tries to run "poetry run" and if that fails, than the file is ran with python directly?

1 Answer 1


I would take advantage of the shell's || operator here:

map <F5> :w<CR>:exe printf('!poetry run %s || python %s', shellescape(@%), shellescape(@%))<CR>

The way this works in the shell is that the || or "or" operator only runs what is on the right-hand side if whatever is on the left-hand side returns with an exit code of 0 (indicating success). It's the same as in || and && in most programming languages:

if False || never_actually_tested:

If you don't want to do that then you need to use some more complex logic and check v:shell_error; I would put that in a function:

fun! s:poetry()
  exe '!poetry' shellescape(@%)
  if v:shell_error > 0
      exe '!python' shellescape(@%)
      " Or: call feedkeys("\<F6>") to run whatever "F6" is.
map <F5> :w<CR>:call <SID>poetry()<CR>
  • 2
    With || short-circuiting bypasses the RHS if the LHS evaluates to true/success. (Since that first line of code is correct this is clearly just a case of a temporary short-circuit in the ol' noggin while writing the description and the never_actually_tested example. :)
    – B Layer
    Jul 29, 2021 at 9:46
  • Thank you! I changed the second line to exe '!poetry run', than it works. But the problem is, when poetry run fails, then I have to Press ENTER or type command to continue I tried to overcome this with changing the 4th line to feedkeys("\<CR>") exe '!python' shellescape(@%), but still have to "press ENTER to continue". Is it possible, to automate this also, so that the 4th line is ran without me having to press ENTER?
    – fl_
    Jul 30, 2021 at 14:40
  • If you don't care about the output of the commands then adding silent in front of them should work @fl_: silent exe '...'. You can also use <silent> in a mapping: map <silent> <F5> .... Use silent! with a ! if you also want to silence error messages. Jul 30, 2021 at 15:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.