%不支持的操作数类型:“字节"和"STR"

编程入门 行业动态 更新时间:2024-10-14 22:18:19
本文介绍了%不支持的操作数类型:“字节"和"STR"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在以下行中收到错误:

I receive the error in the following line:

command = input("please type command.example open 1") #call the serial_connection() function ser.write(b"%d\r\n"%command)

基本上,我希望由用户编写输入并将其解析为ser.write,而不要求输入并将字符串直接放入ser.write中,例如:

Essentially I want the input written by the user and parse it into ser.write, without asking for the input and directly putting the string into ser.write such as:

ser.write(b'close1\r\n')

工作正常,仅当我尝试将输入结果用作字符串以包含在ser.write中时,才会出现问题

worked fine, the problem only occurred when i try to use the result of the input as a string to include in ser.write

更多代码:

ser = 0 #Initialize Serial Port def serial_connection(): COMPORT = int(input("Please enter the port number: ")) ser = serial.Serial() ser.baudrate = 38400 #Suggested rate in Southco documentation, both locks and program must be at same rate ser.port = COMPORT - 1 #counter for port name starts at 0 #check to see if port is open or closed if not ser.isOpen(): print ('The Port %d is open - Will attempt to close lock 1 Stephan: '%COMPORT + ser.portstr) #timeout in seconds ser.timeout = 10 ser.open() command = input("please type command.example open 1") #call the serial_connection() function ser.write(b"%d\r\n"%command) else: print ('The Port %d is **open** Stephan' %COMPORT)

如有任何澄清,请告知.

for any clarification, kindly advise.

推荐答案

也许您可以先尝试解码字节字符串(如果它不是常量字符串,否则就以普通字符串开头),然后应用格式,然后对其进行编码回来吗?

Maybe you can try decoding byte string first (if its not a constant string, otherwise just start with normal string), then applying the format, and then encoding it back?

此外,您应该使用%s而不是%d,因为您的命令是用户直接输入的字符串.

Also, you should use %s instead of %d because your` command is a direct input from user, which is a string.

例如-

ser.write(("%s\r\n"%command).encode())

如果不传递任何参数,则默认为当前系统默认编码,也可以指定要使用的编码,例如utf-8或ascii等.ser.write(("%s\r\n"%command).encode('utf-8'))或ser.write(("%s\r\n"%command).encode('ascii'))

If you do not pass any arguments , it defaults to current system default encoding, you can also specify an encoding to use such as utf-8 or ascii , etc. Example of that - ser.write(("%s\r\n"%command).encode('utf-8')) or ser.write(("%s\r\n"%command).encode('ascii'))

更多推荐

%不支持的操作数类型:“字节"和"STR"

本文发布于:2023-10-28 04:33:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535533.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不支持   字节   类型   操作   STR

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!