【问题标题】:Name error in python with nested function带有嵌套函数的python中的名称错误
【发布时间】:2016-10-12 11:27:59
【问题描述】:

在我的 python 解释器中运行嵌套函数时出错

import MySQLdb
import serial
import time
import smtplib


ser=serial.Serial('/dev/ttyACM1',9600)
db=MySQLdb.connect("localhost","root","pass","db")

cursor=db.cursor()

while 1:
  print("Waiting ;;...")
  print("")
  print("collecting")
  print("")

  time.sleep(3)

  x=ser.readline()
  time.sleep(3)
  if x>700:
     send()
     print"send mail"

  print("inserting into Database")
  sql="INSERT INTO vidit2(temp)  VALUES(%s);" %(x)
  cursor.execute(sql)
  db.commit()
  time.sleep(3)



def send():

 content="send"

 mail=smtplib.SMTP("smtp.gmail.com",587)

 mail.ehlo()

 mail.starttls()

 mail.login("emailid","pass")

 mail.sendmail("sender","reciever",content)

 mail.close()

错误: 蟒蛇临时.py 等待;;...

收集

Traceback(最近一次调用最后一次): 文件“temp.py”,第 24 行,在 发送() NameError:名称“发送”未定义

请帮忙。 提前致谢

【问题讨论】:

    标签: function python-3.x smtpclient


    【解决方案1】:

    不像,比如说,JavaScript 将在编译期间 "hoist" 函数定义,以便它们可以在它们在你的代码中定义之前被调用(前几天才知道这一点,如果这过于简单,请原谅我),在 Python您需要在调用它们之前定义函数(有趣的讨论here)。这意味着您需要这样做:

    def send():
    ...
    

    之前:

    send()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 2018-10-17
      • 2010-10-05
      相关资源
      最近更新 更多