标签归档:vim

为什么从__future__ import print_function使用会破坏Python2样式的打印?[关闭]

问题:为什么从__future__ import print_function使用会破坏Python2样式的打印?[关闭]

我是使用python编程的新手,但我尝试使用分隔符并结束打印,但这仍然给我带来语法错误。

我正在使用python 2.7。

这是我的代码:

from __future__ import print_function
import sys, os, time

for x in range(0,10):
    print x, sep=' ', end=''
    time.sleep(1)

这是错误:

$ python2 xy.py
  File "xy.py", line 5
    print x, sep=' ', end=''
          ^
SyntaxError: invalid syntax
$

I am new at programming with python, and I am trying to print out with a separator and end but it is still giving me a syntax error.

I am using python 2.7.

Here is my code:

from __future__ import print_function
import sys, os, time

for x in range(0,10):
    print x, sep=' ', end=''
    time.sleep(1)

And here is the error:

$ python2 xy.py
  File "xy.py", line 5
    print x, sep=' ', end=''
          ^
SyntaxError: invalid syntax
$

回答 0

首先,from __future__ import print_function必须是脚本中的第一行代码(除了下面提到的一些exceptions)。第二,正如其他答案所说,您现在必须print用作函数。这就是重点from __future__ import print_function;将print 功能从Python 3带入Python 2.6+。

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__语句必须位于文件的顶部,因为它们会更改语言的基本内容,因此编译器需要从一开始就了解它们。从文档中

将来的语句在编译时会得到特殊识别和处理:更改核心结构的语义通常是通过生成不同的代码来实现的。甚至可能是新功能引入了新的不兼容语法(例如新的保留字)的情况,在这种情况下,编译器可能需要以不同的方式解析模块。直到运行时才能推迟此类决策。

该文档还提到,__future__语句之前唯一可以做的事情就是模块文档字符串,注释,空白行和其他将来的语句。

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That’s the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.


使用Vim折叠进行Python代码的推荐方法是什么

问题:使用Vim折叠进行Python代码的推荐方法是什么

我对在Vim中为Python代码启用代码折叠感兴趣。我注意到有多种方法可以做到这一点。

有没有人喜欢在Vim中进行Python代码折叠的首选方法?即

  • 您是否有喜欢并喜欢的特定Vim插件?
  • 您使用手动折叠还是在标记中放置标记?
  • 还有其他推荐的方式在Vim中为Python进行代码折叠吗?

I am interested in enabling code folding in Vim for Python code. I have noticed multiple ways to do so.

Does anyone have a preferred way to do Python code folding in Vim? I.e,

  • Do you have a particular Vim plugin that you use and like?
  • Do you use manual folding or do you place markers in comments?
  • Any other recommended ways to do code folding for Python in Vim?

回答 0

就我个人而言,我无法说服自己用标记乱丢我的代码。我已经习惯于(高效)使用缩进折叠。连同我的空格键映射(请参见下文)以打开/关闭折叠以及zR和zM命令,我就在家里。非常适合Python!

set foldmethod=indent
nnoremap <space> za
vnoremap <space> zf

Personally I can’t convince myself to litter my code with the markers. I’ve become pretty used to (and efficient) at using indent-folding. Together with my mapping of space bar (see below) to open/close folds and the zR and zM commands, I’m right at home. Perfect for Python!

set foldmethod=indent
nnoremap <space> za
vnoremap <space> zf

回答 1

将此语法文件用于Python。它将折叠方法设置为语法,并折叠所有类和函数,但仅此而已。

I use this syntax file for Python. It sets the folding method to syntax and folds all classes and functions, but nothing else.


回答 2

另一个用于折叠Python代码的插件。在GitHub上,处理文档字符串相当简单。

SimpylFold

请享用!

Yet another plugin for folding Python code. Rather simple, handling docstrings, and on the GitHub:

SimpylFold

Enjoy!


回答 3

Python非常适合折叠缩进,有点适合编写我自己的代码,我使用标记,因为它们可以按照您想要的方式压缩文档,并且可以用作目录。我在查看其他人的代码时,在vimrc中可以在两者之间切换。

#Toggle fold methods \fo
let g:FoldMethod = 0
map <leader>fo :call ToggleFold()<cr>
fun! ToggleFold()
    if g:FoldMethod == 0
        exe 'set foldmethod=indent'
        let g:FoldMethod = 1
    else
        exe 'set foldmethod=marker'
        let g:FoldMethod = 0
    endif
endfun
#Add markers (trigger on class Foo line)
nnoremap ,f2 ^wywO#<c-r>0 {{{2<esc>
nnoremap ,f3 ^wywO#<c-r>0 {{{3<esc> 
nnoremap ,f4 ^wywO#<c-r>0 {{{4<esc>
nnoremap ,f1 ^wywO#<c-r>0 {{{1<esc>

Python is well suited for folding on indent, bit for writing my own code I use markers as they can crunch a document down the way you want it and can serve as a kind of a table of contents. I have this in my vimrc to flip between the two when I’m viewing someone elses code.

#Toggle fold methods \fo
let g:FoldMethod = 0
map <leader>fo :call ToggleFold()<cr>
fun! ToggleFold()
    if g:FoldMethod == 0
        exe 'set foldmethod=indent'
        let g:FoldMethod = 1
    else
        exe 'set foldmethod=marker'
        let g:FoldMethod = 0
    endif
endfun
#Add markers (trigger on class Foo line)
nnoremap ,f2 ^wywO#<c-r>0 {{{2<esc>
nnoremap ,f3 ^wywO#<c-r>0 {{{3<esc> 
nnoremap ,f4 ^wywO#<c-r>0 {{{4<esc>
nnoremap ,f1 ^wywO#<c-r>0 {{{1<esc>

回答 4

我认为缩进折叠适合python。我正在为vim-config python / django IDE思想制作一个多分支git repo。叉开!

http://github.com/skyl/vim-config-python-ide

I think that indent folding is fine for python. I’m making a multi-branched git repo for vim-config python/django IDE ideas. Fork away!

http://github.com/skyl/vim-config-python-ide


回答 5

我真的很喜欢这个python_ifold插件


回答 6


回答 7

对我来说,理想的折叠方式是只折叠 classdef折叠,缩进式折叠对于我的口味而言实在太多了。我认为,一个优雅的解决方案是使用的语法系统,这样一个由Tomas提及。但是,该脚本旨在替换原始语法文件,并且最终可能会比原始语法文件旧(即该脚本未提及Python 3语法)。

我的解决方案是将 ~/.vim/syntax文件夹中一个python.vim仅包含重要行的文件(取自上面的脚本):

syn match   pythonDefStatement  /^\s*\%(def\|class\)/
       \ nextgroup=pythonFunction skipwhite
syn region  pythonFunctionFold  start="^\z(\s*\)\%(def\|class\)\>"
       \ end="\ze\%(\s*\n\)\+\%(\z1\s\)\@!." fold transparent

hi link pythonDefStatement Statement

然后只需使用激活折叠即可:set foldmethod=syntax

For me the ideal folding is to fold just the class and def blocks, indent folding is too much for my taste. I think one elegant solution is to use the syntax system like this one mentioned by Tomas. However, this one is meant to replace the original syntax file and it may end being older than the original (i.e. that script doesn’t mention Python 3 syntax).

My solution is to place in the ~/.vim/syntax folder a file named python.vim with just the important lines (taken from the above script):

syn match   pythonDefStatement  /^\s*\%(def\|class\)/
       \ nextgroup=pythonFunction skipwhite
syn region  pythonFunctionFold  start="^\z(\s*\)\%(def\|class\)\>"
       \ end="\ze\%(\s*\n\)\+\%(\z1\s\)\@!." fold transparent

hi link pythonDefStatement Statement

Then simply activate the folding with :set foldmethod=syntax.


回答 8

Python源代码附带一个vim语法插件以及一个自定义vimrc文件。检查vim上python常见问题

The Python source comes with a vim syntax plugin along with a custom vimrc file. Check the python FAQ on vim


回答 9

在您的.vimrc

set foldmethod=indent
set shiftwidth=4

然后zM掩盖所有内容zR以展开所有内容。我还补充说:

nnoremap <space> za
vnoremap <space> zf
map z1  :set foldlevel=0<CR><Esc>
map z2  :set foldlevel=1<CR><Esc>
map z3  :set foldlevel=2<CR><Esc>
map z4  :set foldlevel=3<CR><Esc>
map z5  :set foldlevel=4<CR><Esc>
map z6  :set foldlevel=5<CR><Esc>
map z7  :set foldlevel=6<CR><Esc>
map z8  :set foldlevel=7<CR><Esc>
map z9  :set foldlevel=8<CR><Esc>

这样你就可以z1z2被取消缩进少一点。

In your .vimrc:

set foldmethod=indent
set shiftwidth=4

Then zM to mask all zR to expand all. I also added:

nnoremap <space> za
vnoremap <space> zf
map z1  :set foldlevel=0<CR><Esc>
map z2  :set foldlevel=1<CR><Esc>
map z3  :set foldlevel=2<CR><Esc>
map z4  :set foldlevel=3<CR><Esc>
map z5  :set foldlevel=4<CR><Esc>
map z6  :set foldlevel=5<CR><Esc>
map z7  :set foldlevel=6<CR><Esc>
map z8  :set foldlevel=7<CR><Esc>
map z9  :set foldlevel=8<CR><Esc>

So you can z1 and z2 to unindent little by little.


回答 10

我真的很喜欢我为.vimrc编写的这个小vim脚本。它映射alt+1为折叠第一个python缩进级别(类定义和函数),alt+2折叠第二个python缩进级别(类方法)以及alt+0展开所有内容。它确保仅折叠一个级别,而不折叠任何嵌套的子级别。您仍然可以使用za切换当前块的折叠。请注意,中^[0^[alt用于我的终端。对vim脚本没有太多的经验,所以可以对函数提出建议:)

" Python folding
nnoremap ^[0 zR<CR>
nnoremap ^[1 :call Fold(0)<CR>
nnoremap ^[2 :call Fold(1)<CR>
function Fold(level)
    :let b:max = a:level + 1
    :set foldmethod=indent
    :execute 'set foldnestmax='.b:max
    :execute 'set foldlevel='.a:level
endfunction

I really like this little vim script i wrote for .vimrc. It maps alt+1 to fold the first python indent level (class definitions and functions), alt+2 to fold the second level (class methods), and alt+0 to unfold everything. It makes sure it only folds one level and doesn’t fold any of the nested sub levels. You can still use za to toggle folding for the current block. Note that in ^[0, the ^[ is alt for my terminal. Don’t have a lot of experience in vim script so feel free to make suggestions on the function :)

" Python folding
nnoremap ^[0 zR<CR>
nnoremap ^[1 :call Fold(0)<CR>
nnoremap ^[2 :call Fold(1)<CR>
function Fold(level)
    :let b:max = a:level + 1
    :set foldmethod=indent
    :execute 'set foldnestmax='.b:max
    :execute 'set foldlevel='.a:level
endfunction

在Vim中运行Python代码

问题:在Vim中运行Python代码

我正在使用Vim编写Python代码,每次我想运行我的代码时,都在Vim中键入以下代码:

:w !python

这令人沮丧,所以我一直在寻找一种更快的方法来在Vim中运行Python代码。从终端执行Python脚本吗?我正在使用Linux。

I am writing Python code using Vim, and every time I want to run my code, I type this inside Vim:

:w !python

This gets frustrating, so I was looking for a quicker method to run Python code inside Vim. Executing Python scripts from a terminal maybe? I am using Linux.


回答 0

如何将-添加autocmd到您的~/.vimrc-file,创建映射:

autocmd FileType python map <buffer> <F9> :w<CR>:exec '!python3' shellescape(@%, 1)<CR>
autocmd FileType python imap <buffer> <F9> <esc>:w<CR>:exec '!python3' shellescape(@%, 1)<CR>

然后您可以按<F9>来执行当前缓冲区python

说明:

  • autocmd:Vim将在其上自动执行的命令{event}(此处:如果您打开python文件)
  • [i]map:创建<F9>在插入/普通模式下的键盘快捷键
  • <buffer>:如果打开了多个缓冲区/文件:只需使用活动的缓冲区/文件
  • <esc>:离开插入模式
  • :w<CR>:保存文件
  • !:在您的shell中运行以下命令(尝试:!ls
  • %:替换为活动缓冲区的文件名。但是由于它可以包含空格和其他“坏”的东西,所以最好不要写:python %,而要使用:
  • shellescape:转义特殊字符。该1用反斜杠手段

TL; DR:第一行将在正常模式下工作,一旦按下<F9>它,首先保存文件,然后使用python运行文件。第二个做同样的事情,但是先离开插入模式

How about adding an autocmd to your ~/.vimrc-file, creating a mapping:

autocmd FileType python map <buffer> <F9> :w<CR>:exec '!python3' shellescape(@%, 1)<CR>
autocmd FileType python imap <buffer> <F9> <esc>:w<CR>:exec '!python3' shellescape(@%, 1)<CR>

then you could press <F9> to execute the current buffer with python

Explanation:

  • autocmd: command that Vim will execute automatically on {event} (here: if you open a python file)
  • [i]map: creates a keyboard shortcut to <F9> in insert/normal mode
  • <buffer>: If multiple buffers/files are open: just use the active one
  • <esc>: leaving insert mode
  • :w<CR>: saves your file
  • !: runs the following command in your shell (try :!ls)
  • %: is replaced by the filename of your active buffer. But since it can contain things like whitespace and other “bad” stuff it is better practise not to write :python %, but use:
  • shellescape: escape the special characters. The 1 means with a backslash

TL;DR: The first line will work in normal mode and once you press <F9> it first saves your file and then run the file with python. The second does the same thing, but leaves insert mode first


回答 1

只需按<esc>并输入以下内容即可进入普通模式:

! clear; python %

逐步说明:

! 允许您运行终端命令

clear 将清空您的终端屏幕

; 结束第一个命令,使您可以引入第二个命令

python将使用python运行脚本(ruby例如可以替换为脚本 )

%合并当前文件名,并将其作为参数传递给 python命令

Just go to normal mode by pressing <esc> and type:

! clear; python %

Step by step explanation:

! allows you to run a terminal command

clear will empty your terminal screen

; ends the first command, allowing you to introduce a second command

python will use python to run your script (it could be replaced with ruby for example)

% concats the current filename, passing it as a parameter to the python command


回答 2

我的.vimrc文件中有这个:

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

完成Python脚本的编辑后,只需按<F5>。保存脚本,然后在空白屏幕中执行。

I have this in my .vimrc file:

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

When I’m done editing a Python script, I just press <F5>. The script is saved and then executed in a blank screen.


回答 3

我更喜欢将Python输出重定向到新的Vim窗口(如果该窗口保持打开状态,则下次使用此函数执行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

I prefer Python output redirected to a new Vim window (and if that window is left open then update its content the next time you execute Python code with this function):

" 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

回答 4

基于前面的答案,如果您希望在查看代码输出时看到代码,则可以找到: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在第二行中使用时,代码以垂直分割而不是水平分割运行。

不利的是,如果不关闭代码运行所在的拆分窗口,则在多次运行后您将有很多拆分(这在原始的python IDLE中不会发生,在该Python IDLE中重复使用了相同的输出窗口)。

(我将这些行留在里面/home/user/.vimrc

Building on the previous answers, if you like to see the code while looking at its’ output you could find :ter (:terminal) command useful.

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

Using vert in the second line runs the code in vertical split instead of horizontal.

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)


回答 5

请记住,您可以使用来重复上次使用的命令@:,因此您只需要重复这两个字符即可。

或者,您可以将字符串保存w !python到其中一个寄存器中("a例如),然后单击:<C-R>a<CR>以将寄存器的内容插入a命令行并运行它。

或者你可以做我想做的,并映射<leader>z:!python %<CR>运行当前文件。

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.


回答 6

如果您不想:exec python file.py每次看到“ ”打印,请使用以下命令:

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

它也没有弄乱我的电源线/ vim-航空公司状态栏。

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.


回答 7

插件:jupyter-vim

因此,您可以向正在运行的行(替换)发送行(<leader>E),视觉选择()<leader>ejupyter-clientipython

我更喜欢将编辑器和解释器分开(每个都在其外壳中)。假设您发送了错误的输入阅读命令…

Plugin: jupyter-vim

So you can send lines (<leader>E), visual selection (<leader>e) to a running jupyter-client (the replacement of ipython)

I prefer to separate editor and interpreter (each one in its shell). Imagine you send a bad input reading command …


回答 8

对于一般用途(基于,从vim运行python / haskell / ruby​​ / C ++ … filetype),有一个不错的插件,称为vim-quickrun。默认情况下,它支持多种编程语言。它也很容易配置,因此可以根据需要为任何文件类型定义首选行为。github仓库没有花哨的自述文件,但doc文件对此进行了很好的记录。

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.


回答 9

可接受的答案对我有用(在Linux上),但是我希望此命令在运行之前也可以保存缓冲区,因此我对其进行了一些修改:

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

:w <bar>然后保存缓冲中运行的代码。

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>

The :w <bar> saves the buffer THEN runs the code in it.


回答 10

一种简单的方法是:在正常模式下键入内容,然后按键盘上的向上箭头键,然后按Enter。这将在VIM上重复最后键入的命令。

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.


回答 11

如果您想快速跳回:w命令,可以输入以下内容:w,然后按向上箭头。它只会循环搜索以开头的命令w

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.


回答 12

我的.vimrc上有这个:

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

这将保存当前缓冲区并仅使用Esc + F9执行代码

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


回答 13

您也可以使用skywind3000 / asyncrun.vim。它类似于@FocusedWolf列出的内容。

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


回答 14

您可以使用augroup命令通过1个键盘绑定扩展到任何语言,例如:

augroup rungroup
    autocmd!
    autocmd BufRead,BufNewFile *.go nnoremap <F5> :exec '!go run' shellescape(@%, 1)<cr>
    autocmd BufRead,BufNewFile *.py nnoremap <F5> :exec '!python' shellescape(@%, 1)<cr>
augroup END

You can extends for any language with 1 keybinding with augroup command, for example:

augroup rungroup
    autocmd!
    autocmd BufRead,BufNewFile *.go nnoremap <F5> :exec '!go run' shellescape(@%, 1)<cr>
    autocmd BufRead,BufNewFile *.py nnoremap <F5> :exec '!python' shellescape(@%, 1)<cr>
augroup END


回答 15

考虑使用shebang行,这样您就可以使用任何语言,而不仅限于Python。

添加shebang:

将此添加到脚本的第一行:

#!/usr/bin/env python3

或者,如果您使用的是Python 2:

#!/usr/bin/env python2

Vim键盘映射:

将此添加到您的~/.vimrc

nmap <F7> :w<cr>:!clear;"%:p"<cr>

使文件可执行:

输入Vim:

:!chmod +x %

或在终端:

chmod +x script_name.py

说明:

在正常模式下按F7时,Vim会尝试将当前文件作为bash脚本执行。然后,bash解释器将看到shebang行并了解该文件应传递给Python(或在需要时传递给其他程序)。

另外,您将能够使用其名称从终端运行脚本:

./script_name.py

而不是这种方式(也可以):

python3 script_name.py

Think about using shebang line, so you will be able to use it with still any language, not only Python.

Adding shebang:

Add this to first line of your script:

#!/usr/bin/env python3

or this, if you are using Python 2:

#!/usr/bin/env python2

Vim keymap:

Add this to your ~/.vimrc:

nmap <F7> :w<cr>:!clear;"%:p"<cr>

Make file executable:

Type in Vim:

:!chmod +x %

or in terminal:

chmod +x script_name.py

Explanation:

When F7 is pressed in normal mode, Vim will try to execute current file as bash script. Then bash interpreter will see shebang line and understand, that this file should be passed to Python (or any other programm if needed).

Also you will be able to run your script from terminal using it’s name:

./script_name.py

instead of this way (that will work too):

python3 script_name.py

回答 16

此.vimrc映射需要Conque Shell,但它会复制Geany(和其他X编辑器)的行为:

  • 按一个键执行
  • 在gnome-terminal中执行
  • 等待确认退出
  • 窗口在退出时自动关闭

    :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; \" "')

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; \" "')


回答 17

将光标放在代码中的某个位置。右键单击并选择“选择”选项之一以突出显示您的代码。然后按Ctrl:您将看到新的提示“ <,>”

现在输入!python,看看是否可行。

我只是花几天的时间来找出同样的问题!!!我使用了编码:

s='My name'
print (s) 

拔完头发后,我终于弄对了!

Put your cursor in the code somewhere. Right click and choose one of the “Select” choices to highlight your code. Then press Ctrl : and you will see the new prompt ‘<, >’

Now type !python and see if that works.

I just spend days trying to figure out the same problem!!! I used the coding:

s='My name'
print (s) 

After I pulled out all my hair, I finally got it right!


回答 18

不要将命令映射放入您的中.vimrc,而是将映射放入~/.vim/ftplugin/python.vim文件中(Windows $HOME\vimfiles\ftplugin\python.vim)。如果您没有此文件或目录,请进行创建。这样,仅当您打开.py文件或任何带有的文件时,才会映射键filetype=python,因为您将仅在Python脚本上运行此命令。

对于实际的映射,我希望能够在脚本运行时在Vim中进行编辑。从@cazyas的答案出发,我在ftplugin\python.vimWindows中有以下内容:

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

这将在后台运行当前的Python脚本。对于Linux,只需将其更改为:

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

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>

回答 19

" run current python file to new buffer
function! RunPython()
    let s:current_file = expand("%")
    enew|silent execute ".!python " . shellescape(s:current_file, 1)
    setlocal buftype=nofile bufhidden=wipe noswapfile nowrap
    setlocal nobuflisted
endfunction
autocmd FileType python nnoremap <Leader>c :call RunPython()<CR>
" run current python file to new buffer
function! RunPython()
    let s:current_file = expand("%")
    enew|silent execute ".!python " . shellescape(s:current_file, 1)
    setlocal buftype=nofile bufhidden=wipe noswapfile nowrap
    setlocal nobuflisted
endfunction
autocmd FileType python nnoremap <Leader>c :call RunPython()<CR>

如何在Vim中注释掉Python代码块

问题:如何在Vim中注释掉Python代码块

我想知道Vim中是否有任何键映射可以让我缩进某些代码行(无论这些行是在可视模式下选择的,还是在当前光标位置上方/下方的n行)。

所以基本上是可以转换以下内容的东西

def my_fun(x, y):
    return x + y

#def my_fun(x, y):
#    return x + y

我可以使用#"""注释掉相关行。理想情况下,如果给定的行已被注释掉,我也希望使用相同的键盘映射来取消注释。

I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or n lines above/below current cursor position).

So basically something that converts the following

def my_fun(x, y):
    return x + y

to

#def my_fun(x, y):
#    return x + y

I am okay with using either # or """ for commenting out the relevant lines. Ideally, I would also like the same keymapping to uncomment the lines if the given lines have been commented out.


回答 0

步骤1:转到要评论的第一行的第一列。

步骤2:按:Ctrl+,v然后选择要注释的行:

步骤3: ShiftI#space(进入插入-在左模式,键入字符插入的选择将消失,但在其内的所有线将在步骤4之后进行修改)

第4步: Esc

Step 1: Go to the the first column of the first line you want to comment.

Step 2: Press: Ctrl+v and select the lines you want to comment:

Step 3: ShiftI#space (Enter Insert-at-left mode, type chars to insert. The selection will disappear, but all lines within it will be modified after Step 4.)

Step 4: Esc


回答 1

手动方式

:set number
:10,12s/^/#

one way manually

:set number
:10,12s/^/#

回答 2

您可以将以下映射添加到您的.vimrc中

vnoremap <silent> # :s/^/#/<cr>:noh<cr>
vnoremap <silent> -# :s/^#//<cr>:noh<cr>

突出显示您的方块:

Shift+v

# 在第一列中注释您的行。

-# 以相同的方式取消注释。

You could add the following mapping to your .vimrc

vnoremap <silent> # :s/^/#/<cr>:noh<cr>
vnoremap <silent> -# :s/^#//<cr>:noh<cr>

Highlight your block with:

Shift+v

# to comment your lines from the first column.

-# to uncomment the same way.


回答 3

突出显示您的方块: ShiftV

用以下方式注释掉选定的块:(:norm i#小写i)

要取消注释,请再次突出显示您的方块,并取消注释: :norm ^x

:norm命令为每个选定的行执行一个动作。注释将#在每行的开头插入一个,而注释不删除将删除该行#

Highlight your block with: ShiftV

Comment the selected block out with: :norm i# (lower case i)

To uncomment, highlight your block again, and uncomment with: :norm ^x

The :norm command performs an action for every selected line. Commenting will insert a # at the start of every line, and uncommenting will delete that #.


回答 4

我通常会扫出一个可视块(<C-V>),然后搜索并用以下内容替换第一个字符:

:'<,'>s/^/#

(进入选择了可视块的命令模式后,自动在命令行上放置了“ <,”>)然后,我可以通过清除相同的可视块来取消注释该块,并:

:'<,'>s/^#//

I usually sweep out a visual block (<C-V>), then search and replace the first character with:

:'<,'>s/^/#

(Entering command mode with a visual block selected automatically places ‘<,’> on the command line) I can then uncomment the block by sweeping out the same visual block and:

:'<,'>s/^#//

回答 5

有一些不错的插件可以帮助注释/取消注释行。例如NERD Commenter

There are some good plugins to help comment/uncomment lines. For example The NERD Commenter.


回答 6

我的代码如下.vimrc

" comment line, selection with Ctrl-N,Ctrl-N
au BufEnter *.py nnoremap  <C-N><C-N>    mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>`n
au BufEnter *.py inoremap  <C-N><C-N>    <C-O>mn<C-O>:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap  <C-N><C-N>    mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>gv`n

" uncomment line, selection with Ctrl-N,N
au BufEnter *.py nnoremap  <C-N>n     mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>:s/^#$//ge<CR>:noh<CR>`n
au BufEnter *.py inoremap  <C-N>n     <C-O>mn<C-O>:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR><C-O>:s/^#$//ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap  <C-N>n     mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>gv:s/#\n/\r/ge<CR>:noh<CR>gv`n

快捷方式会保留您的光标位置和注释,只要它们以#(以#开头)为开头即可。例如:

# variable x
x = 0

评论后:

# variable x
#x = 0

取消理解后:

# variable x
x = 0

I have the following lines in my .vimrc:

" comment line, selection with Ctrl-N,Ctrl-N
au BufEnter *.py nnoremap  <C-N><C-N>    mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>`n
au BufEnter *.py inoremap  <C-N><C-N>    <C-O>mn<C-O>:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap  <C-N><C-N>    mn:s/^\(\s*\)#*\(.*\)/\1#\2/ge<CR>:noh<CR>gv`n

" uncomment line, selection with Ctrl-N,N
au BufEnter *.py nnoremap  <C-N>n     mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>:s/^#$//ge<CR>:noh<CR>`n
au BufEnter *.py inoremap  <C-N>n     <C-O>mn<C-O>:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR><C-O>:s/^#$//ge<CR><C-O>:noh<CR><C-O>`n
au BufEnter *.py vnoremap  <C-N>n     mn:s/^\(\s*\)#\([^ ]\)/\1\2/ge<CR>gv:s/#\n/\r/ge<CR>:noh<CR>gv`n

The shortcuts preserve your cursor position and your comments as long as they start with # (there is space after #). For example:

# variable x
x = 0

After commenting:

# variable x
#x = 0

After uncomennting:

# variable x
x = 0

回答 7

坦白说,我对该链接使用了tcomment插件。它几乎可以处理所有语法。它定义了不错的动作,将其与一些特定于python的文本块匹配器配合使用,使其成为一个功能强大的工具。

Frankly I use a tcomment plugin for that link. It can handle almost every syntax. It defines nice movements, using it with some text block matchers specific for python makes it a powerful tool.


回答 8

NERDcommenter是一个出色的注释插件,可以自动检测多种文件类型及其关联的注释字符。使用Pathogen易于安装。

用进行评论<leader>cc。取消注释<leader>cu。并使用切换评论<leader>c<space>

<leader>vim中的默认键是\

NERDcommenter is an excellent plugin for commenting which automatically detects a number of filetypes and their associated comment characters. Ridiculously easy to install using Pathogen.

Comment with <leader>cc. Uncomment with <leader>cu. And toggle comments with <leader>c<space>.

(The default <leader> key in vim is \)


回答 9

vim有很多注释插件-其中许多是多语言的-不只是python。如果您使用Vundle之类的插件管理器,则可以使用以下命令搜索它们(一旦安装了Vundle):

:PluginSearch comment

您将获得一个结果窗口。或者,您可以只在vim脚本中搜索注释插件

There’s a lot of comment plugins for vim – a number of which are multi-language – not just python. If you use a plugin manager like Vundle then you can search for them (once you’ve installed Vundle) using e.g.:

:PluginSearch comment

And you will get a window of results. Alternatively you can just search vim-scripts for comment plugins.


回答 10

无需插件或映射。尝试使用内置的“规范”命令,该命令实际上会在每条选定的行上执行所需的任何操作。

添加#条评论

1. shift V to visually select lines
2. :norm i#

删除#条评论

1. visually select region as before
2. :norm x

或者,如果您的评论缩进了,您可以 :norm ^x

请注意,这些只是普通的vim命令,其前面带有“:norm”以在每一行上执行它们。

在此处的答案之一中使用“ norm”命令的更详细的答案

在Vim中注释/取消注释行的快速方法是什么?

No plugins or mappings required. Try the built-in “norm” command, which literally executes anything you want on every selected line.

Add # Comments

1. shift V to visually select lines
2. :norm i#

Remove # Comments

1. visually select region as before
2. :norm x

Or if your comments are indented you can do :norm ^x

Notice that these are just ordinary vim commands being preceded by “:norm” to execute them on each line.

More detailed answer for using “norm” command in one of the answers here

What’s a quick way to comment/uncomment lines in Vim?


回答 11

一个非常轻巧的插件:vim-commentary。

gcc注释一行
gcgc以取消注释。查看插件页面了解更多信息。

v+k/j突出显示该块,然后gcc评论该块。

A very minimal light weight plugin: vim-commentary.

gcc to comment a line
gcgc to uncomment. check out the plugin page for more.

v+k/j highlight the block then gcc to comment that block.


回答 12

CtrlK 进行评论(可视模式):

vnoremap <silent> <C-k> :s#^#\##<cr>:noh<cr>

CtrlU 取消注释(可视模式):

vnoremap <silent> <C-u> :s#^\###<cr>:noh<cr>

CtrlK for comment (Visual Mode):

vnoremap <silent> <C-k> :s#^#\##<cr>:noh<cr>

CtrlU for uncomment (Visual Mode):

vnoremap <silent> <C-u> :s#^\###<cr>:noh<cr>

Qutebrowser-基于PyQt5的键盘驱动、类似VIM的浏览器

QuteBrowser是一款以键盘为中心的浏览器,具有最小的GUI。它基于Python和PyQt5以及GPL许可的自由软件

它的灵感来自于其他浏览器/插件,如DWB和Vperator/Pentadactyl

QuteBrowser的主要维护人员-Compiler目前在捐款的资助下兼职开发QuteBrowser要使这种情况持续很长时间,需要您的帮助!请参阅GitHub Sponsors page了解更多信息。根据您的注册日期和保持一定级别的时间,您可以获得QuteBrowser T恤、贴纸等!

下载次数

请参阅github releases
page
有关可用的下载和INSTALL有关如何在各种平台上运行QuteBrowser的详细说明,请参阅

文档和获取帮助

请参阅help page有关可用的文档页面和支持频道

贡献/错误

您想为QuteBrowser做贡献吗?太棒了!请阅读the contribution guidelines以获取详细信息和有用的提示

如果您发现错误或有功能请求,可以通过以下几种方式进行报告:

有关安全漏洞,请直接通过以下地址与我联系mail@qutebrowser.org,GPG ID0x916eb0c8fd55a072

要求

运行QuteBrowser需要以下软件和库:

  • Python3.6.1或更高版本
  • Qt带有以下模块的5.12.0或更高版本(建议使用5.12 LTS或5.15):
    • QtCore/qtbase
    • QtQuick(在某些发行版中是qtbase或qt声明性的一部分)
    • QtSQL(某些发行版中的qtbase的一部分)
    • QtDBus(在某些发行版中是qtbase的一部分;请注意,在运行时连接到DBus是可选的)
    • QtOpenGL
    • QtWebEngine,或
    • 或者QtWebKit(5.212)-不建议这样做由于QtWebKit中已知的安全问题,您很可能希望使用具有默认QtWebEngine后端(基于Chromium)的quteBrowser。引用QtWebKit releases page[最新的QtWebKit]版本基于[一个]旧的WebKit版本,其中包含已知的未打补丁的漏洞。请谨慎使用,避免访问不可信的网站和用于传输敏感数据
  • PyQt适用于Python 3的5.12.0或更高版本
  • jinja2
  • PyYAML

在较早的Python版本(3.6/3.7/3.8)上,还需要以下后端口:

以下库是可选的:

  • adblock(对于使用ABP语法改进的广告阻止)
  • pygments对于语法突出显示,请使用:view-source在QtWebKit上,或在使用:view-source --pygments使用(默认)QtWebEngine后端
  • 在Windows上,colorama对于彩色日志输出
  • importlib_resources在Python3.7或更早版本上,当通过pip安装PyQtWebEngine时,为了改进QtWebEngine版本检测(因此,此依赖项通常与打包程序无关)
  • asciidoc要生成文档,请执行以下操作:help命令,当使用git存储库(而不是发行版)时。

看见the documentation有关如何安装QuteBrowser及其依赖项的说明

捐赠

QuteBrowser的主要维护人员-Compiler目前在捐款的资助下兼职开发QuteBrowser要使这种情况持续很长时间,需要您的帮助!请参阅GitHub Sponsors page了解更多信息。根据您的注册日期和保持一定级别的时间,您可以获得QuteBrowser T恤、贴纸等!

GitHub赞助商允许一次性捐款(使用“选择级别”旁边的按钮)和自定义金额。对于欧元或瑞士法郎以外的货币,这是首选的捐赠方式GitHub使用Stripe接受信用卡付款,不收取任何费用。通过PayPal付款也是可用的,费用比直接PayPal交易要少

或者,也可以使用以下捐赠方式, - 请注意,是否有资格获得礼品(衬衫/贴纸/等)请按具体情况处理。get in touch有关详细信息,请参阅

  • 国家环保总局欧洲境内银行转账(不收费):
    • 账户持有人:弗洛里安·布鲁欣(Florian Bruhin)
    • 国家:瑞士
    • 伊班(欧元):CH13 0900 0000 9160 4094 6
    • IBAN(其他):CH800 0900 0000 8711 8587 3
    • 银行:PostFinance AG,Mingerstrasse 20,3030 Bern,Swiss(BIC:POFICHBEXXX)
    • 如果您需要任何其他信息:请通过以下方式与我联系mail@qutebrowser.org
  • 贝宝:CHFEURUSD注:费用可能非常高(根据捐赠金额的不同,约为5-40%)-考虑使用GitHub赞助商(接受信用卡或贝宝!)或SEPA银行转账
  • 加密货币:
    • 比特币:bc1q3ptyw8hxrcfz6ucfgmglphfvhqpy8xr6k25p00
    • 比特币现金:1BnxUbnJ5MrEPeh5nuUMx83tbiRAvqJV3N
    • 以太:0x10c2425856F7a8799EBCaac4943026803b1089c6
    • Litecoin:MDt3YQciuCh6QyFmr8TiWNxB94PVzbnPm2
    • 其他:请get in touch,我很乐意设置任何东西supported by Ledger Live

赞助商

非常感谢MacStadium通过其免费托管的Mac Mini支持QuteBrowserOpen Source Project

(他们不需要在这里包括这些-我只是对他们的提议非常满意,没有他们,就不会有MacOS版本或测试)

多亏了HSR Hochschule für Technik Rapperswil,这使得将quteBrowser扩展作为学生研究项目进行研究成为可能。


作者

QuteBrowser的主要作者是Florian Bruhin(编译器),但是如果没有hundreds of contributors好了!

此外,以下人员还提供了图形:

  • Jad/yelo(新建图标)
  • WOFALL(原始图标)
  • regines(密钥绑定小抄)

另外,感谢为QuteBrowser的其中一个项目做出贡献的每一个人crowdfunding campaigns好了!

类似的项目

像QuteBrowser这样有着相似目标的项目还有很多。在某种程度上,他们中的许多人都是QuteBrowser的灵感来源,谢谢你!

活动的

不活动

许可证

本程序是自由软件:您可以根据自由软件基金会发布的GNU通用公共许可证的条款、许可证的版本3或(根据您的选择)对其进行再分发和/或修改

分发本程序的目的是希望它有用,但没有任何担保;甚至没有对适销性或是否适用于特定目的的默示担保。有关更多详细信息,请参阅GNU通用公共许可证

您应该已经收到此程序附带的GNU通用公共许可证副本。如果没有,请参见https://www.gnu.org/licenses/gpl-3.0.txt

pdf.js

QuteBrowser可以选择使用pdf.js要在浏览器中显示PDF文件,请执行以下操作。Windows版本附带捆绑的pdf.js

pdf.js是按照Apache许可证的条款分发的。您可以在以下位置找到许可证的副本qutebrowser/3rdparty/pdfjs/LICENSE(在Windows发行版中或在运行scripts/dev/update_3rdparty.py)或在线here