函数不在Python中返回值

时间:2018-03-09 14:13:05

标签: python-3.x raspberry-pi3

我已经编写了一个代码来读取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()

谢谢!

2 个答案:

答案 0 :(得分:0)

您没有看到任何错误,因为您在except:块中吞并了它们 - 您所做的只是回滚事务。尝试在raise之后立即放置rollback,这样您就可以看到出现了什么问题(并使用close()添加了最终版本):

try:
    # some stuff

except:
    db.rollback()
    raise

finally:
    cur.close()

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

答案 1 :(得分:0)

我无法测试此代码,因为它与我所相信的是Raspberry-Pi或其克隆。

假设您没有测量0开尔文校准或科学测量,我将假设您永远不会测量0 K.(这将在以后变得明确)

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

首先,您的代码无论如何都无法调用您的主要/主要功能。我强烈建议将以下两行添加到代码的底部,这将在脚本运行时调用main函数:

        $item = $model->where('id',$id);

        function deepProcess($item,$depth,$currentRel,$currentRelClasses) {
            foreach ($depth->first()->getPossibleRelations() as $rel) {//eager load any possible relations
                $newRel = $rel;
                if ($currentRel !== '') {
                    $newRel = $currentRel.'.'.$rel;// $newRel example, dog.owner.addresses
                }

                $futureItemCollection = $depth->first()->$rel->first();
                if (!$futureItemCollection) {
                    continue; // no relationship found from $depth through $rel
                }
                array_push($currentRelClasses, get_class($futureItemCollection));//we need to check for the future relationship before the recursive call
                if (max(array_count_values($currentRelClasses)) > 1) {//if we've hit the same relation more than once then skip current iteration
                    continue;
                }

                // $fillable = $futureItemCollection->getFillable();
                // $item = $item->with([$newRel => function($query) use($fillable) {
                //     call_user_func_array([$query, 'select'], $fillable);//select only fillable fields
                // }]);
                $item = $item->with($newRel);//selecting only fillable fields wasn't working, likely due to unexpected fields being required
                $item = deepProcess($item, $depth->first()->$rel,$newRel,$currentRelClasses);
            }
            return $item;
        }
        $item = deepProcess($item,$item,'',[get_class($item->first())])->get()->toArray();
        dd($item);

这个主函数,你将所有代码都包含在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() 。您假设退货有多行,或者完全有效。如果没有有效的读取,你需要返回一些东西,返回值为0 Kelvin(= -273.15 C),所以如果你得到那个值,你知道没有实际的读数。你可以把它改成你认为合适的东西,我只需要选择一些东西。例如:

read_temperature()

您要执行的下一步操作是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之类的东西。由于我不熟悉您的数据库,您可能需要自己更改。