Is there a clean alias that I can put in my vimrc that will run the current file using python if there is a python extension?
At the moment I have nnoremap <leader>r :!%:p<Enter> as suggested in this question (when I hit \+r it runs the open file). It works great for bash files, where the convention is to add a shebang line and make the file executable, but for python files it obviously exits 1.
As a workaround I have added a new command - command PyBang :call append(0, "#!/usr/bin/env python") - that adds a python shebang to the top of the file. The problem is that this is not really convention for .py files and making them all executable seems like a lot of effort for some reason.
So I am struggling to write an alias that will run :!%:p<Enter> if there is no extension and prepend python if there is a .py extension on the file in the buffer.
Any ideas are really appreciated.
The easiest way to do this is to use vim's exclamation mark to run shell commands. For instance,
: ! python3 % will run the current file % with python3 outside of vim, in whatever shell you're in.
You can use this in combination with vim scripting to create your own shortcuts for this command.
To combine this with your current bash function, you will need conditional logic in your vim function to detect filetypes (see here and here for how to work with filetypes and their detection)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With