繁体   English   中英

函数未在Python中返回值

[英]Function not returning value in Python

我已经编写了一个代码来读取Raspberry Pi的python中的开关,温度和日期。 当我单独运行每个程序而没有函数定义时,它运行良好。 当我结合所有它不会给出任何结果。

def ReadSwitch():

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    while True:
        input_state = GPIO.input(17)
        if input_state == False:
            print(input_state)
            return input_state

def ReadTemprature():
    os.system('modprobe w1-gpio')
    os.system('modprobe w1-therm')

    temp_sensor = 'sys/bus/w1/devices/28-041600c3c0ff/w1_slave'
    print(temp_sensor)

    f = open(temp_sensor, 'r')
    lines = f.readlines()
    f.close()
    temp_output = lines[1].find('t=')

    if temp_output!=-1:
        temp_string=lines[1].strip()[temp_output+2:]
        temp_c=float(temp_string)/1000.0
        temp_f=temp_c * 9.0/5.0+32.0
        print(temp_c, temp_f)
        time.sleep(1)
        return temp_c

def GetDateTime():
    date = date.today()
    now = (date)
    return now


def InsertSmartBoxData():
    db = MySQLdb.connect(host = "localhost", user = "root", passwd = "sa", db = "SmartPayloadBox")
    cur = db.cursor()

    try:
        temp = ReadTemprature()
        switch = ReadSwitch()
        time = GetDateTime()


        cur.execute("INSERT INTO SmartPayloadBox.SmartBoxData(temprature,tamper,time) VALUES(%s,%s,%s)",(temp,switch,time))
        db.commit()           

    except:
        db.rollback()

    cur.close()

谢谢!

您没有看到任何错误,因为您将它们吞入了您的except:块中—您所做的所有事情都是回滚事务。 尝试在rollback后立即raise ,这样就可以看到出了什么问题(并使用close()添加一个finally):

try:
    # some stuff

except:
    db.rollback()
    raise

finally:
    cur.close()

另一种可能性是这些功能根本没有运行。 正如@match所指出的那样,在向我们展示的代码中,没有任何地方调用主函数InsertSmartBoxData

我无法测试此代码,因为它与我所相信的是Raspberry-Pi或此类代码的克隆集成在一起。

假设您未测量0开尔文(Kelvin)校准或科学测量值,那么我假设您将永远不必测量0K。(稍后将变得很清楚)

让我分析您的代码,并提供一些改进代码的提示。 我将变量和函数的某些名称更改为“ snake_case ”,这更像pythonic

首先,您的代码始终没有调用您的主要/主要功能。 我会强烈建议在代码底部添加以下两行,这将在运行脚本时调用您的主函数:

if __name__ == '__main__':
    insert_smart_box_data()

这个主要功能是将所有代码封装在try/except块中,我相信您应该进行更改,因此对函数的调用在该块外,而数据库更新在该块内,例如:

def insert_smart_box_data():
    # call your functions
    temp = read_temprature()
    switch = read_switch()
    time = get_date_time()
    # open the database connection
    db = MySQLdb.connect(host = "localhost", user = "root", passwd = "sa", db = "SmartPayloadBox")
    cur = db.cursor()    
    # update record
    try:
        cur.execute("INSERT INTO SmartPayloadBox.SmartBoxData(temprature,tamper,time) VALUES(%s,%s,%s)",(temp,switch,time))
        db.commit()           
    except:
        db.rollback()
        raise
    finally:
        cur.close()

您调用的第一个函数是read_temperature() 您假设退货单有多行,或者根本无效。 如果没有有效的读数,则需要返回某个值,该值的返回值为0开尔文(= -273.15 C),因此,如果获得该值,则表明没有实际的读数。 您可以将其更改为您认为合适的任何东西,我只需要选择一些即可。 例:

def read_temprature():
    # set variables
    temp_c = -273.15
    # do system commands
    os.system('modprobe w1-gpio')
    os.system('modprobe w1-therm')
    # set filename
    temp_sensor = 'sys/bus/w1/devices/28-041600c3c0ff/w1_slave'
    print(temp_sensor)
    # read the file
    with open(temp_sensor, 'r') as f:
        lines = f.readlines()
    # check that you indeed have a lines[1]
    if len(lines) > 1:
        temp_output = lines[1].find('t=')
        if temp_output != -1:
            temp_string = lines[1].strip()[temp_output+2:]
            temp_c = float(temp_string)/1000.0
            temp_f = temp_c * 9.0/5.0+32.0
            print(temp_c, temp_f)
            # not sure why you are sleeping for a second
            # consider taking this out
            time.sleep(1)
    return temp_c

您要做的下一个动作是read_switch() ,如果input_state仍然为True则这可以是不确定的循环。 因此,我建议使用可配置的max_tries 例:

def read_switch(max_tries=10):
    # set default variables
    input_state = True
    # GPIO commands
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    # only loop until max_tries
    for _ in range(max_tries):
        input_state = GPIO.input(17)
        if input_state == False:
            print(input_state)
            break
    return input_state

然后,您可以将日期/时间函数简化为:

def get_date_time():
    return date.today()

我没有测试的方法,但是将所有内容放在一起是这样的:

def read_switch(max_tries=10):
    # set default variables
    input_state = True
    # GPIO commands
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    # only loop until max_tries
    for _ in range(max_tries):
        input_state = GPIO.input(17)
        if input_state == False:
            print(input_state)
            break
    return input_state

def read_temprature():
    # set variables
    temp_c = -273.15
    # do system commands
    os.system('modprobe w1-gpio')
    os.system('modprobe w1-therm')
    # set filename
    temp_sensor = 'sys/bus/w1/devices/28-041600c3c0ff/w1_slave'
    print(temp_sensor)
    # read the file
    with open(temp_sensor, 'r') as f:
        lines = f.readlines()
    # check that you indeed have a lines[1]
    if len(lines) > 1:
        temp_output = lines[1].find('t=')
        if temp_output != '-1':
            temp_string = lines[1].strip()[temp_output+2:]
            temp_c = float(temp_string)/1000.0
            temp_f = temp_c * 9.0/5.0+32.0
            print(temp_c, temp_f)
            # not sure why you are sleeping for a second
            # consider taking this out
            time.sleep(1)
    return temp_c

def get_date_time():
    return date.today()

def insert_smart_box_data():
    # call your functions
    temp = read_temprature()
    switch = read_switch()
    time = get_date_time()
    # open the database connection
    db = MySQLdb.connect(host = "localhost", user = "root", passwd = "sa", db = "SmartPayloadBox")
    cur = db.cursor()    
    # update record
    try:
        cur.execute("INSERT INTO SmartPayloadBox.SmartBoxData(temprature,tamper,time) VALUES(%s,%s,%s)",(temp,switch,time))
        db.commit()           
    except:
        db.rollback()
        raise
    finally:
        cur.close()

if __name__ == '__main__':
    insert_smart_box_data()

现在,您确实需要更改try/except块。 您应该只捕获需要捕获的内容。 except SomeError类的东西,然后raise SomeExcpetion 由于我不熟悉您的数据库,因此您可能需要自行更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM