0

我的 python 脚本中的标识有时会突然变成,我想你可以说是损坏了。标识会突然改变,使我的程序失败。

如果我使用 cat 查看文件,我可以看到标识是错误的。但在 VIM 中它显示得很好。这是输出和设置,

有任何想法吗 ???

通过'cat -e'

              validate_hostname = RegexValidator(regex=r'[a-zA-Z0-9-_]*\.[a-zA-Z]{2,6}',message="Enter a valid hostname.")$
           validate_hostname(host_input)$
   except ValidationError, e:$
               print type(e)$
       print str(e[0])$
       error = str(e)$

else:$
       error = "Please complete all fields."       $
   $
   print error$
   return [error,host_input,record_input]$

在 VIM 中

                   validate_hostname = RegexValidator(regex=r'[a-zA-Z0-9-_]*\.[a-zA-Z]{2,6}',message="Enter a valid hostname.")
                   validate_hostname(host_input)
           except ValidationError, e:
               print type(e)
               print str(e[0])
               error = str(e)
       else:
           error = "Please complete all fields."

       print error
       return [error,host_input,record_input]

我的.vimrc看起来像,

syntax on
se bg=dark
set tabstop=4      " insert 4 spaces when a tab is pressed
set shiftwidth=4   " change the number of space characters inserted for indentation
set expandtab      " insert spaces whenver a tab key is pressed
4

2 回答 2

3

It looks like you have mixed spaces and tabs. The code looks different in vim and in cat -e (or simply less) because they use different width for the tab, due to your set tabstop=4.

If in vim it looks fine, then doing :retab should fix it: it will replace tab characters with the amount of spaces as you see it. The result will look the same, but all tab characters will be gone.

It's important to have the right tabstop value before you do retab. For example if you have the opposite problem--code looks correct in less but broken in vim, and you do :retab in that state, that will break the Python script.

Check out this fantastic article about tabs in vim:

http://vimcasts.org/episodes/tabs-and-spaces/

In particular, I think you should add these settings to your .vimrc:

set softtabstop=4
set smarttab
于 2013-09-21T08:19:45.783 回答
0

特别是在 Python 中,空格很重要,你不应该混合制表符和空格。即使您在 Vim 中仔细设置了缩进设置(甚至可能在每个文件中包含模式行来设置缩进),编辑该文件的其他用户也可能不会太在意。

因此,我编写了IndentConsistencyCop 插件,它可以验证缩进,并在不一致时进行投诉。插件页面有其他插件的链接。

于 2013-09-21T14:52:55.473 回答