programing tip

Vim에서 Python 코드 실행

itbloger 2020. 9. 21. 07:25
반응형

Vim에서 Python 코드 실행


저는 Vim을 사용하여 Python 코드를 작성하고 있으며 코드를 실행하고 싶을 때마다 Vim에 다음을 입력합니다.

:w !python

이것은 실망스러워서 Vim 내에서 Python 코드를 실행하는 더 빠른 방법을 찾고있었습니다. 터미널에서 Python 스크립트를 실행하고 있습니까? Linux를 사용하고 있습니다.


을 추가하는 방법 autocmd, 때 FileType python, 매핑을 만듭니다.

nnoremap <buffer> <F9> :exec '!python' shellescape(@%, 1)<cr>

그런 다음을 눌러 <F9>현재 버퍼를 실행할 있습니다.python


내 .vimrc 파일에 다음이 있습니다.

imap <F5> <Esc>:w<CR>:!clear;python %<CR>

Python 스크립트 편집이 끝나면 키를 누릅니다 <F5>. 스크립트가 저장되고 빈 화면에서 실행됩니다.


을 누르고 다음 <esc>을 입력 하여 일반 모드로 이동하십시오 .

! clear; python %

여기에 이미지 설명 입력

단계별 설명 :

! 터미널 명령을 실행할 수 있습니다.

clear 터미널 화면을 비 웁니다

; 두 번째 명령을 도입 할 수 있도록 첫 번째 명령을 종료합니다.

pythonpython을 사용하여 스크립트를 실행합니다 ( ruby예를 들어 대체 할 수 있음 ).

%현재 파일 이름을 연결하여 python명령에 매개 변수로 전달합니다.


새 Vim 창으로 리디렉션되는 Python 출력을 선호합니다 (그리고 해당 창이 열려있는 경우 다음에이 함수로 Python 코드를 실행할 때 해당 내용을 업데이트합니다).

" Bind F5 to save file if modified and execute python script in a buffer.
nnoremap <silent> <F5> :call SaveAndExecutePython()<CR>
vnoremap <silent> <F5> :<C-u>call SaveAndExecutePython()<CR>

function! SaveAndExecutePython()
    " SOURCE [reusable window]: https://github.com/fatih/vim-go/blob/master/autoload/go/ui.vim

    " save and reload current file
    silent execute "update | edit"

    " get file path of current file
    let s:current_buffer_file_path = expand("%")

    let s:output_buffer_name = "Python"
    let s:output_buffer_filetype = "output"

    " reuse existing buffer window if it exists otherwise create a new one
    if !exists("s:buf_nr") || !bufexists(s:buf_nr)
        silent execute 'botright new ' . s:output_buffer_name
        let s:buf_nr = bufnr('%')
    elseif bufwinnr(s:buf_nr) == -1
        silent execute 'botright new'
        silent execute s:buf_nr . 'buffer'
    elseif bufwinnr(s:buf_nr) != bufwinnr('%')
        silent execute bufwinnr(s:buf_nr) . 'wincmd w'
    endif

    silent execute "setlocal filetype=" . s:output_buffer_filetype
    setlocal bufhidden=delete
    setlocal buftype=nofile
    setlocal noswapfile
    setlocal nobuflisted
    setlocal winfixheight
    setlocal cursorline " make it easy to distinguish
    setlocal nonumber
    setlocal norelativenumber
    setlocal showbreak=""

    " clear the buffer
    setlocal noreadonly
    setlocal modifiable
    %delete _

    " add the console output
    silent execute ".!python " . shellescape(s:current_buffer_file_path, 1)

    " resize window to content length
    " Note: This is annoying because if you print a lot of lines then your code buffer is forced to a height of one line every time you run this function.
    "       However without this line the buffer starts off as a default size and if you resize the buffer then it keeps that custom size after repeated runs of this function.
    "       But if you close the output buffer then it returns to using the default size when its recreated
    "execute 'resize' . line('$')

    " make the buffer non modifiable
    setlocal readonly
    setlocal nomodifiable
endfunction

이 작업에는 많은 노력이 필요 했으므로 관대하다고 느끼면 페이팔 기부를 자유롭게 보내주십시오. :)


이전 답변을 바탕으로 출력을 보면서 코드를보고 싶다면 :ter( :terminal) 명령이 유용하다는 것을 알 수 있습니다.

autocmd Filetype python nnoremap <buffer> <F5> :w<CR>:ter python2 "%"<CR>
autocmd Filetype python nnoremap <buffer> <F6> :w<CR>:vert ter python3 "%"<CR>

사용하여 vert두 번째 줄에있는 것은 수직 분할 대신 수평의 코드를 실행합니다.

The negative of it is that if you don't close the split-window where the code ran you will have many splits after multiple runs (which doesn't happen in original python IDLE where the same output window is reused).

(I keep these lines inside /home/user/.vimrc)


Keep in mind that you're able to repeat the last used command with @:, so that's all you'd need to repeat are those two character.

Or you could save the string w !python into one of the registers (like "a for example) and then hit :<C-R>a<CR> to insert the contents of register a into the commandline and run it.

Or you can do what I do and map <leader>z to :!python %<CR> to run the current file.


If you don't want to see ":exec python file.py" printed each time, use this:

nnoremap <F9> :echo system('python2 "' . expand('%') . '"')<cr>
nnoremap <F10> :echo system('python3 "' . expand('%') . '"')<cr>

It didn't mess up my powerline / vim-airline statusbar either.


A simple method would be to type : while in normal mode, and then press the up arrow key on the keyboard and press Enter. This will repeat the last typed commands on VIM.


If you want to quickly jump back through your :w commands, a cool thing is to type :w and then press your up arrow. It will only cycle through commands that start with w.


For generic use (run python/haskell/ruby/C++... from vim based on the filetype), there's a nice plugin called vim-quickrun. It supports many programming languages by default. It is easily configurable, too, so one can define preferred behaviours for any filetype if needed. The github repo does not have a fancy readme, but it is well documented with the doc file.


I have this on my .vimrc:

"map <F9> :w<CR>:!python %<CR>"

which saves the current buffer and execute the code with presing only Esc + F9


You can use skywind3000/asyncrun.vim as well. It is similar to what @FocusedWolf has listed.


This .vimrc mapping needs Conque Shell, but it replicates Geany (and other X editors') behaviour:

  • Press a key to execute
  • Executes in gnome-terminal
  • Waits for confirmation to exit
  • Window closes automatically on exit

    :let dummy = conque_term#subprocess('gnome-terminal -e "bash -c \"python ' . expand("%") . '; answer=\\\"z\\\"; while [ $answer != \\\"q\\\" ]; do printf \\\"\nexited with code $?, press (q) to quit: \\\"; read -n 1 answer; done; \" "')


Instead of putting the command mapping in your .vimrc, put the mapping in your ~/.vim/ftplugin/python.vim file (Windows $HOME\vimfiles\ftplugin\python.vim). If you don't have this file or directories, just make them. This way the key is only mapped when you open a .py file or any file with filetype=python, since you'll only be running this command on Python scripts.

For the actual mapping, I like to be able to edit in Vim while the script runs. Going off of @cazyas' answer, I have the following in my ftplugin\python.vim (Windows):

noremap <F5> <Esc>:w<CR>:!START /B python %<CR>

This will run the current Python script in the background. For Linux just change it to this:

noremap <F5> <Esc>:w<CR>:!python % &<CR>

The accepted answer works for me (on Linux), but I wanted this command to also save the buffer before running, so I modified it slightly:

nnoremap <buffer> <F9> :w <bar> :exec '!python' shellescape(@%, 1)<cr>

:w <bar>다음 버퍼를 저장 그것의 코드를 실행합니다.


코드 어딘가에 커서를 놓습니다. 마우스 오른쪽 버튼을 클릭하고 "선택"항목 중 하나를 선택하여 코드를 강조 표시하십시오. 그런 다음 Ctrl 키를 누르면 새 프롬프트 '<,>'가 표시됩니다.

이제! python을 입력하고 작동하는지 확인하십시오.

나는 단지 같은 문제를 알아 내려고 며칠을 보낸다 !!! 코딩을 사용했습니다.

s='My name'
print (s) 

머리카락을 모두 뽑은 후 드디어 맞았습니다!

참고 URL : https://stackoverflow.com/questions/18948491/running-python-code-in-vim

반응형