【问题标题】:TypeError: float() argument must be a string or a number, not 'NoneType'TypeError:float() 参数必须是字符串或数字,而不是“NoneType”
【发布时间】:2018-06-13 16:06:32
【问题描述】:

我知道很多人都问过相关问题,但请帮助我。我正在尝试复制我在网上找到的开源温度控制实验室。我想在树莓派上运行它。 这是我不断收到的错误:

    Traceback (most recent call last):
  File "/home/pi/Desktop/Python/test_Temperature.py", line 14, in <module>
    print('Temperature 1: ' + str(a.T1) + ' degC')
  File "/home/pi/Desktop/Python/tclab.py", line 26, in T1
    self._T1 = float(self.read('T1'))
TypeError: float() argument must be a string or a number, not 'NoneType'

生成它的代码是这样的:

import tclab
import numpy as np
import time

try:
    # Connect to Arduino
    a = tclab.TCLab()

    # Get Version
    print(a.version)

    # Temperatures
    print('Temperatures')
    print('Temperature 1: ' + str(a.T1) + ' degC')
    print('Temperature 2: ' + str(a.T2) + ' degC')

    # Turn LED on
    print('LED On')
    a.LED(100)

    # Turn on Heaters (0-100%)
    print('Turn On Heaters (Q1=90%, Q2=80%)')
    a.Q1(90.0)
    a.Q2(80.0)

    # Sleep (sec)
    time.sleep(60.0)

    # Turn Off Heaters
    print('Turn Off Heaters')
    a.Q1(0.0)
    a.Q2(0.0)

    # Temperatures
    print('Temperatures')
    print('Temperature 1: ' + str(a.T1) + ' degC')
    print('Temperature 2: ' + str(a.T2) + ' degC')

# Allow user to end loop with Ctrl-C           
except KeyboardInterrupt:
    # Disconnect from Arduino
    a.Q1(0)
    a.Q2(0)
    print('Shutting down')
    a.close()

# Make sure serial connection still closes when there's an error
except:           
    # Disconnect from Arduino
    a.Q1(0)
    a.Q2(0)
    print('Error: Shutting down')
    a.close()
    raise

我相信该代码试图通过以下代码与另一个 python 文件进行通信:

import sys
import time
import numpy as np
try:
    import serial
except:
    import pip
    pip.main(['install','pyserial'])
    import serial
from serial.tools import list_ports

class TCLab(object):

    def __init__(self, port=None, baud=9600):
        if (sys.platform == 'darwin') and not port:
            port = '/dev/ttyACM1'

    def stop(self):
        return self.read('X')

    def version(self):
        return self.read('VER')

    @property
    def T1(self):
        self._T1 = float(self.read('T1'))
        return self._T1

    @property
    def T2(self):
        self._T2 = float(self.read('T2'))
        return self._T2

    def LED(self,pwm):
        pwm = max(0.0,min(100.0,pwm))/2.0
        self.write('LED',pwm)
        return pwm

    def Q1(self,pwm):
        pwm = max(0.0,min(100.0,pwm)) 
        self.write('Q1',pwm)
        return pwm

    def Q2(self,pwm):
        pwm = max(0.0,min(100.0,pwm)) 
        self.write('Q2',pwm)
        return pwm

    # save txt file with data and set point
    # t = time
    # u1,u2 = heaters
    # y1,y2 = tempeatures
    # sp1,sp2 = setpoints
    def save_txt(self,t,u1,u2,y1,y2,sp1,sp2):
        data = np.vstack((t,u1,u2,y1,y2,sp1,sp2))  # vertical stack
        data = data.T                 # transpose data
        top = 'Time (sec), Heater 1 (%), Heater 2 (%), ' \
          + 'Temperature 1 (degC), Temperature 2 (degC), ' \
          + 'Set Point 1 (degC), Set Point 2 (degC)' 
        np.savetxt('data.txt',data,delimiter=',',header=top,comments='')

    def read(self,cmd):
        cmd_str = self.build_cmd_str(cmd,'')
        try:
            self.sp.write(cmd_str.encode())
            self.sp.flush()
        except Exception:
            return None
        return self.sp.readline().decode('UTF-8').replace("\r\n", "")

    def write(self,cmd,pwm):       
        cmd_str = self.build_cmd_str(cmd,(pwm,))
        try:
            self.sp.write(cmd_str.encode())
            self.sp.flush()
        except:
            return None
        return self.sp.readline().decode('UTF-8').replace("\r\n", "")

    def build_cmd_str(self,cmd, args=None):
        """
        Build a command string that can be sent to the arduino.

        Input:
            cmd (str): the command to send to the arduino, must not
                contain a % character
            args (iterable): the arguments to send to the command
        """
        if args:
            args = ' '.join(map(str, args))
        else:
            args = ''
        return "{cmd} {args}\n".format(cmd=cmd, args=args)

    def close(self):
        try:
            self.sp.close()
            print('Arduino disconnected successfully')
        except:
            print('Problems disconnecting from Arduino.')
            print('Please unplug and reconnect Arduino.')
        return True

我还不知道我周围的 python 代码,所以对解决方案的一个非常清晰的“虚拟类”解释真的很有帮助。谢谢大家。

【问题讨论】:

  • 你了解类和对象的区别吗?
  • 可能不像专业人士那样详细,但我相当理解这个概念

标签: python string nonetype


【解决方案1】:

这是read() 函数:

def read(self,cmd):
    cmd_str = self.build_cmd_str(cmd,'')
    try:
        self.sp.write(cmd_str.encode())
        self.sp.flush()
    except Exception:
        return None
    return self.sp.readline().decode('UTF-8').replace("\r\n", "")

它可以返回的东西之一是 None,正如您在 return None 行中看到的那样。如果发生这种情况,那么您的行:

float(self.read('T1'))

会失败,因为它会尝试将 None 转换为 float,这会导致您遇到错误。

【讨论】:

  • 非常感谢您的及时回复。请问,如何改正?
  • 我将 None 更改为 0。程序运行但只给了我值 0。请问我该如何有效地纠正这个问题?
  • @TochukwuAnyaduba try/except 构造是为了捕获 self.sp.write 行中的错误。如果发生某些错误,则错误会被消除,而您会得到 None(现在是 0 以及您的编辑)。换句话说,您在写入串行端口时遇到了某种错误,并且错误正在被代码静音,而是返回零。您的设备可能未连接到串行端口,或者您有其他问题。我不知道代码是否完整,但我根本找不到 self.sp 的定义位置,所以您可能错过了定义?
  • 再次感谢您。你说得很对。这不是完整的代码。这些文件可以在这里找到:github.com/jckantor/TCLab/tree/master/tclab
  • 我终于让代码工作了。显然,当 Arduino Leonardo 通过 USB 连接到我的 Pi 时,我试图通过串行通信,我也没有使用适用于 Linux 的 Arduino IDE,所以它一直在崩溃。现在一切顺利。代码没有问题
猜你喜欢
  • 2022-01-09
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 2017-08-29
  • 1970-01-01
  • 2019-07-07
相关资源
最近更新 更多