Curangle()抛出此错误 - TypeError:float()参数必须是字符串或数字

时间:2016-01-26 23:53:32

标签: linux python-3.x

以下是原始代码:

    #Update the solar file for reporting
logsolar = open('/tools/inputs/solarvalues.txt','w')
writeline=("[myvars]\n")
logsolar.write(writeline)
writeline=("solar_heading: " + str(round((float(getsolarheading())),1)) + "\n")
logsolar.write(writeline)
writeline=("solar_elevation: " + str(round((float(getsolarangle())),1))+ "\n")
logsolar.write(writeline)
writeline=("actual_elevation: " + str(round((float(getcurangle())),1))+ "\n")
logsolar.write(writeline)
writeline=("actual_heading: " + str(round((float(getcurheading())),1))+ "\n")
logsolar.write(writeline)
logsolar.close()

以下是错误消息:

    Traceback (most recent call last):
  File "solarrobot7-core.py", line 373, in <module>
    writeline=("actual_elevation: " + str(round((float(getcurangle())),1))+ "\n")
TypeError: float() argument must be a string or a number
为此,我已经浏览了七页Google,但仍然无法弄清楚如何对此行进行编码,以便它不会抛出此错误。对不起,花了这么久。以下是首次调用curangle()的地方。

#Read the IMU to get the angle of incline (forwards/backwards)
#This is what we use for the solar panels, so we have to switch
#from 0 degrees on the normal axis to 0 degrees on the horizon
def getcurangle():
    # The escape character for # is \x23 in hex
    serialport.write(b"\x23o0 \x23f")
    response = serialport.readline()
    words = response.split(b",")
    if len(words) > 2:
        try:
            if ((float(words[1]) -90) * -1) < 89:
                curangle = ((float(words[1]) -90) * -1)
            else:
                curangle = 0
        except:
            curangle = 999
        return curangle + AngleOffset

.split(b“,”)中的“b”被添加到原始代码中,据说可以在Python-3.x下运行此代码。

1 个答案:

答案 0 :(得分:0)

忽略异常,如果响应没有要分割的“,”字符,则单词[1]将不会被填充,也不能转换为浮点数。 首先检查以确保响应中包含来自代码中其他位置的逗号的逗号。

您还可以通过添加print response然后print words[1]来检查这一点,以确保单词[1]返回的是数字而不是空值。

使用except,我们可以假设返回值总是一个int(单词[1]是一个int并返回,或者单词[1]不是int而999是从except返回的)所以错误来自AngleOffset。 仔细检查AngleOffset的值。