2

I know we can run a.py in vim using commands:

:! python a.py    " method 1
:! python %       " method 2

We can also set key binding to run python script as:

autocmd! FileType python nmap ,r :!clear; python %<CR>

Now the problem is if we have to pass the arguments, I tried to create a command like this:

command py !python %   " This does not work!!

Required:
:py arg1 arg2 should run python script with arguments arg1 and arg2, i.e. python a.py arg1 arg2

Example python script:

import sys
print(sys.argv[1])
print(sys.argv[2])

I am using vim in Macbook Pro.

$ vim --version
VIM - Vi IMproved 8.0 (2016 Sep 12, compiled Nov 29 2017 18:37:46)
Included patches: 1-503, 505-680, 682-1283
Compiled by [email protected]
1
  • 5
    All user-defined commands must start with a capital letter. Thus, you are not permitted to define :py, but can define :Py. :help user-cmd-ambiguous Commented Jun 6, 2018 at 3:46

1 Answer 1

3
command! -nargs=* Py !python % <args>

-nargs=* allows any number of arguments (0, 1, or many). <args> pastes command-line arguments into the command.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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