如何防止python中的名称错误错误?
当我运行我的程序core.py(http://pastebin.com/kbzbBUYd)返回:如何防止python中的名称错误错误?
文件 “core.py”,第47行,在texto core.mail(numbersendlist,MessageText中) NameError:全局命名的 '芯' 是未定义
任何人都可以告诉我发生了什么以及如何阻止此错误?
如果有帮助,在core.py的“进口承运人”行指carrier.py(http://pastebin.com/zP2RHbnr)
你得到了NameError
因为在你的代码中没有在本地或全局范围内定义的名称core
。在调用它的方法之前先创建一个Core
对象。
另外,texto()
的缩进可能是错误的。您将无法从模块的其余部分使用此功能。如果您想从当前模块的其他部分或其他模块使用它,请在模块级别声明该功能,或者使用@staticmethod
装饰器,以便使其成为该类的静态方法。
这应该工作。
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import carrier
class Core:
def __init__(self, username, password):
# code could be added here to auto load these from a file
self.gmail_user = username
self.gmail_pwd = password
# Send one text to one number
# TODO: send to multiple addresses
def mail(self, to, text):
msg = MIMEMultipart()
msg['From'] = self.gmail_user
msg['To'] = to
msg.attach(MIMEText(text))
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(self.gmail_user, self.gmail_pwd)
mailServer.sendmail(self.gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
def texto(sendtoaddress, messagetext):
numbersendlist = []
for number in sendtoaddress:
numbersendlist.append(carrier.carriercheck(number))
core = Core('username', 'password')
for number in numbersendlist:
core.mail(number, messagetext)
texto(['1112223333'], 'hi. this better work.')
返回: 回溯(最近通话最后一个): 文件 “new.py”,第42行,在
哦,等等,我的一些缩进是错误的。它会生成:http://pastebin.com/npx3d8ci – ErikT 2010-02-28 18:18:51
因为您在每次迭代中将整个列表发送到“mail()”,而不是字符串。修复了我回复中的代码。 – Imran 2010-02-28 18:26:58
core
是不是你已经确定,但一个名字。我希望你打算写点类似
core = Core('username', 'password')
打电话之前texto
?
应该只是“邮件”而不是“core.mail”呢?因为我试过,但得到: 文件“core.py”,第47行,在texto 邮件(numbersendlist,messagetext) NameError:全局名称'邮件'未定义 我只是想运行“邮件”功能从我的texto功能。 – ErikT 2010-02-28 17:52:46
你的代码没有第47行,所以首先我会说你应该与你的代码同步你的文章。 – hughdbrown 2010-02-28 17:54:48
谢谢。我改变了pastebin页面。 – ErikT 2010-02-28 18:03:18