python3不合理地返回TabError:缩进中不一致地使用制表符和空格

2024-04-19 15:37:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不熟悉。我发现我的python代码返回不合理的return tab错误:

msgs['to']=“xxx@gmail.com”
^ TabError:缩进中不一致地使用制表符和空格

以下是我的部分代码:

def send_email(self):
    try:
        msgs = MIMEMultipart()
        msgs['to'] = "xxx"
        msgs['from'] = "xxx"
        msgs['subject'] = "abc"
        msgs.attach(MIMEText(file("~/att1.py").read())
        msgs.attach(MIMEText(file("~/att2.docx").read())

        server = smtplib.SMTP()
        server.connect('smtp.gmail.com:587')
        server.login('xxx','xxx')
        server.sendmail(msgs['from'], msgs['to'],msgs.as_string())
        server.quit()
        print "Successfully sent email"
        return True
    except SMTPException:
        print "Error: unable to send email"
        print str(SMTPException)
        return False

Tags: to代码fromcomsendreturnserveremail
1条回答
网友
1楼 · 发布于 2024-04-19 15:37:34

您的代码确实不一致地使用了制表符空间。当复制原始文章以升华文本3,然后选择所有行时,我可以同时看到制表符(行)和空格(点):

enter image description here

注意,我将tabs设置为expand to8 spaces,这也是Python所做的。请注意msgs[..]行现在甚至不再排成一行。在Python 3中混合使用制表符和空格进行缩进也是一个语法错误。

将文本编辑器配置为在使用TAB键时插入空格。这是Python代码的推荐配置,因为tab宽度依赖于编辑器配置,而空格的宽度总是相同的。这是Python styleguide (PEP 8)建议的:

Tabs or Spaces?

Never mix tabs and spaces.

The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!

For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do.

相关问题 更多 >