format在python中的常见错误_为什么在python warnings.formatwarning on format string中会出现编码错误?...

在Python2.x中,str是字节字符串,unicode是Unicode字符的字符串。若将str和unicode混合使用,Python默认用ASCII编码转换,会出现编码或解码错误。原因可能是传入对象非str或unicode,如warnings.warn()不接受unicode消息。解决办法是避免混合使用,需用unicode时确保所有字符串为unicode。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

您正在混合unicode和str对象。

说明:

在Python2.x中,有两种对象可以包含文本字符串。str和unicode。str是一个字节字符串,因此它只能包含0到255之间的字符。

Unicode是Unicode字符的字符串。

可以使用“encode”和“decode”方法在str和unicode之间进行转换:>>> "thisisastring".decode('ascii')

u'thisisastring'

>>> u"This is ä string".encode('utf8')

'This is \xc3\xa4 string'

注意编码。编码是将unicode文本表示为字节字符串的方法。

如果尝试将str和unicode添加到一起,Python将尝试将其中一个转换为另一个。但默认情况下,它将使用ASCII作为编码,这意味着a-z、a-z和一些额外的字符,如!"#$%&/()=?'{[]]}等。其他任何字符都将失败。

此时,您将得到一个编码错误或解码错误,这取决于Python是否尝试将unicode转换为str或str转换为unicode。通常它会尝试解码,即转换为unicode。但有时它决定不去,而是强迫去串。我不完全确定为什么。

更新:

上面出现编码错误而不是解码错误的原因是上面代码中的message既不是str也不是unicode。它是另一个对象,它有一个str方法。因此,Python在传入str(message)之前会执行str(message),但这会失败,因为内部存储的消息是一个不能强制转换为ascii的unicode对象。

或者更简单的回答是:它失败是因为warnings.warn()不接受unicode消息。

现在,解决方案:

不要混合str和unicode。如果你需要使用unicode,而且你显然需要,那么试着确保所有的字符串都是unicode。这是确保你避免这种情况的唯一方法。这意味着,无论何时从磁盘读取字符串,或调用可能返回纯ascii str以外任何内容的函数,都应尽快将其解码为unicode。

当您需要将它保存到磁盘或通过网络发送或传递给不理解unicode的方法时,请尽可能晚地将其编码到str。

在这种特定情况下,问题是您将unicode传递给warnings.warn(),而您不能这样做。传递字符串。如果您不知道它是什么(这里似乎是这样),因为它来自其他地方,您的try/except解决方案与repr一起工作很好,尽管做一个编码是可能的。

from PyQt6.QtCore import QTimer, QByteArray from PyQt6.QtGui import QPixmap from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QProgressBar, QCheckBox from S08dome import Ui_Form from S08mode2 import Ui_Form1 from serial_son import SerialThread from arcade import load_sound, play_sound, stop_sound import serial.tools.list_ports import warnings class sonwindow(QWidget,Ui_Form1): def __init__(self): super().__init__() self.setupUi(self) class MyWindow(QWidget, Ui_Form): def __init__(self): super().__init__() self.setupUi(self) self.setWindowTitle("Serial Com") self.serial_thread = None self.open_serial_flag = False self.zdon = False self.num = False self.num1 = False self.checkBox.clicked.connect(self.hex_sx) self.checkBox_2.clicked.connect(self.hex_fs) self.pushButton.clicked.connect(lambda :self.plainTextEdit.clear()) self.pushButton_7.clicked.connect(self.mode) self.pushButton_8.clicked.connect(self.baoj) self.pushButton_11.clicked.connect(self.zp) self.pushButton_12.clicked.connect(self.nobaoj) self.horizontalSlider_4.valueChanged.connect(self.up) self.spinBox_3.valueChanged.connect(self.dowm) self.horizontalSlider_3.valueChanged.connect(self.up2) self.spinBox_4.valueChanged.connect(self.dowm2) self.pushButton_2.clicked.connect(self.open_serial_modbus) self.pushButton_6.clicked.connect(self.sx_ck) self.pushButton_4.clicked.connect(self.send) self.pushButton_3.clicked.connect(self.son) self.checkBox_3.setChecked(False) self.lineEdit_2 self.timer = QTimer(self) #######进度条 self.jdt_cz = 0 self.flat = 1 self.run = False self.progressBar_2.setValue(self.jdt_cz) self.progressBar_2.setRange(0,100) self.pushButton_9.clicked.connect(self.fx_flag) self.timer = QTimer(self) self.timer.timeout.connect(self.update) def hex_sx(self): self.num = not self.num def hex_fs(self): self.num1 = not self.num1 def fx_flag(self): if self.openmen == False: if not self.run: # 如果定时器未运行,启动并设置方向 self.run = True self.timer.start(50) # 间隔50ms else: # 如果定时器在运行,切换方向 self.flat *= -1 def update(self): self.jdt_cz += self.flat # 边界保护 if self.openmen == False: if self.jdt_cz >= 100: self.jdt_cz = 100 self.timer.stop() self.run = False self.flat = -1 # 下次自动反向 self.lineEdit_6.setText("打开") self.pp = False elif self.jdt_cz <= 0: self.jdt_cz = 0 self.timer.stop() self.run = False self.flat = 1 # 下次自动反向 self.lineEdit_6.setText("关闭") self.pp = True self.progressBar_2.setValue(self.jdt_cz) ###子页面 def son(self): self.son_1 = sonwindow() self.son_1.show() ###滑条 def up(self,num): self.horizontalSlider_4.setValue(num) self.spinBox_3.setValue(num) def dowm(self,num): self.horizontalSlider_4.setValue(num) self.spinBox_3.setValue(num) def up2(self,num2): self.horizontalSlider_3.setValue(num2) self.spinBox_4.setValue(num2) def dowm2(self,num2): self.horizontalSlider_3.setValue(num2) self.spinBox_4.setValue(num2) def mode(self): self.mode = not self.mode if self.mode: self.lineEdit_10.setText("自动") self.openmen = True # self.zidon() else: self.lineEdit_10.setText("手动") self.openmen = False ###按键切换标签内容 def zidon(self): if self.openmen == True and self.yv == False: self.lineEdit_6.setText("关闭") else: self.lineEdit_6.setText("打开") #######MP3 def baoj(self): if self.pp == False: self.label_23.setStyleSheet("background-color: rgb(255, 0, 0);border-radius:30px;") sound = load_sound("蜂鸣器哔哔响.mp3") self.player = play_sound(sound) self.lineEdit_6.setText("关闭") def nobaoj(self): self.label_23.setStyleSheet("background-color: rgb(0, 85, 0);border-radius:30px;") sound = load_sound("蜂鸣器哔哔响.mp3") player = play_sound(sound) stop_sound(player) ######来回切换图片 def zp(self): self.zp = not self.zp if self.zp: self.label_25.setPixmap(QPixmap("不下雨.png")) self.yv = True else: self.label_25.setPixmap(QPixmap("下雨.jpg")) self.yv = False # def yvzhi(self): # try: # # 将字符串转换为浮点数(假设 self.wd, self.max, self.min 是数值字符串) # current_temp = float(self.wd) # upper_limit = float(self.max) # lower_limit = float(self.min) # # # 判断温度是否超出阈值 # if current_temp > upper_limit or current_temp < lower_limit: # self.label_22.setStyleSheet("background-color: rgb(0, 255, 0); border-radius: 30px;") # else: # self.label_22.setStyleSheet("background-color: rgb(0, 85, 0); border-radius: 30px;") # except ValueError as e: # print(f"数据格式错误: {e}") # except AttributeError as e: # print(f"属性缺失: 确保已接收到数据 - {e}") ###########串口 def sx_ck(self): self.comboBox.clear() serial_ports = serial.tools.list_ports.comports() for port in serial_ports: self.comboBox.addItem(port.device) def open_serial_modbus(self): self.open_serial_flag = not self.open_serial_flag databits = int(8) stopbits = int(1) parity = serial.PARITY_NONE if self.open_serial_flag: self.pushButton_2.setText("关闭串口") self.label_2.setPixmap(QPixmap("指示灯常亮.png.png")) port = self.comboBox.currentText() baudrate = int(self.comboBox_2.currentText()) try: self.serial_thread = SerialThread(port, baudrate, databits,parity,stopbits) self.serial_thread.data_received.connect(self.FirstReader) self.serial_thread.start() except Exception as e: print(f"无法连接到串口 {port}: {str(e)}") else: self.pushButton_2.setText("打开串口") self.label_2.setPixmap(QPixmap("指示灯熄灭.png")) self.serial_thread.serial_client.close() # 改进后的指令发送方法 # def send_custom_instruction_with_delay(self): # try: # # if self.hex_display == False: # instruction = bytes.fromhex(str(self.plainTextEdit_2.toPlainText()))##16 # self.send_protocol(instruction) # # # else: # # instruction = str(self.plainTextEdit_2.toPlainText()).encode("GBK")##字符串 # # self.send_protocol(instruction) # except Exception as e: # print(f"发送指令时发送错误: {e}") # # def send_protocol(self, protocol): # if hasattr(self, 'serial_thread') and self.serial_thread.isRunning(): # self.serial_thread.serial_client.write(protocol) # print("协议发送成功.") # else: # print("串行Modbus RTU连接未打开.") def send(self): if self.num1: self.serial_thread.serial_client.write(bytes.fromhex(str(self.plainTextEdit_2.toPlainText()))) else: self.serial_thread.serial_client.write(str(self.plainTextEdit_2.toPlainText()).encode("GBK")) def format_data(self, data): return ' '.join(f"{byte:02X}" for byte in data) def FirstReader(self, information): if self.num: self.plainTextEdit.appendPlainText(self.format_data(information)) else: try: shu = bytes.fromhex(self.format_data(information).replace(" ", "")).decode("GBK") self.plainTextEdit.appendPlainText(shu) except Exception as e: self.plainTextEdit.appendPlainText(str(e)) self.lineEdit_9.setText(str(int(str(self.format_data(information).split(" ")[1]), 16))) self.lineEdit_7.setText(str(int(self.format_data(information).split(" ")[2], 16))) self.lineEdit_8.setText(str(int(self.format_data(information).split(" ")[3], 16))) # # if self.hex_display == False: # formatted_data = self.format_data(information) # 将接收到的数据格式化为十六进制 # self.plainTextEdit.appendPlainText(f"接收到的信息是:{formatted_data}") # print(f"{formatted_data}") # # else: # # self.plainTextEdit.appendPlainText(f"{information}") ##字符串 # #print(f"{information}") # # # # # self.data_strip = information.strip(" ") # data_hex1 = self.data_strip.upper().encode().hex() # data_hex = self.format_data(data_hex1.encode("gbk")) # byte_array = QByteArray.fromHex(information.encode('utf-8')) # self.hex_data.append(byte_array) # # # 使用GBK编码解码为字符串 # byte_array = QByteArray.fromHex(information.encode('utf-8')) # # # 将 QByteArray 转换为 bytes,然后解码为字符串 # decoded_string = byte_array.data().decode('GBK') # # if self.hex_str: # self.plainTextEdit.appendPlainText(f"{data_hex}") # else: # self.plainTextEdit.appendPlainText(f"{decoded_string}") #######串口读取数据 # def FirstReader(self, information): # self.plainTextEdit.appendPlainText(f"{information}") # self.num1 = information.split(" ")[1].split(" ")[0] # self.num2 = information.split(" ")[2].split(" ")[0] # self.num3 = information.split(" ")[3].split(" ")[0] # self.wd = self.num1.split(" ")[0].strip(" ") # self.max = self.num2.split(" ")[0].strip(" ") # self.min = self.num3.split(" ")[0].strip(" ") # self.lineEdit_9.setText(str(self.wd)) # self.lineEdit_7.setText(str(self.max)) # self.lineEdit_8.setText(str(self.min)) # self.yvzhi() if __name__ == '__main__': warnings.filterwarnings("ignore", category=DeprecationWarning) app = QApplication([]) window = MyWindow() window.show() app.exec()用我程序里的定时器将串口上报数据定时发送 并告诉我添加的部分
最新发布
05-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值