當我運行我的程序core.py(http://pastebin.com/kbzbBUYd)返回:如何防止python中的名稱錯誤錯誤?
文件 「core.py」,第47行,在texto core.mail(numbersendlist,MessageText中) NameError:全局命名的 '芯' 是未定義
任何人都可以告訴我發生了什麼以及如何阻止此錯誤?
如果有幫助,在core.py的「進口承運人」行指carrier.py(http://pastebin.com/zP2RHbnr)
當我運行我的程序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