通过Pyserial ascii格式发送终端命令

发布于 2025-01-20 10:16:04 字数 673 浏览 2 评论 0原文

我想创建一个像终端一样的 Python 程序来使用 Pyserial 发送一些请求。

但是,当我发送“dataid 60000 get value”之类的请求时,它会向我显示一条错误消息,例如: 类型错误:不支持 unicode 字符串,请编码为字节:'dataid 60000 get value'

我尝试使用 .encode 但没有结果。

请参阅下面的代码:

#Modules
from base64 import encode
import serial

port = "COM5"
baud = 115200

#Serial port configuration
com = serial.Serial(port, baud, timeout=1)

if com.isOpen():
    print(com.name + ' is open...')

#Print output
while True:
    cmd = input("Enter command or 'exit':")
    if cmd == 'exit':
        com.close()
        exit()
    else:
        com.write(cmd)
        out = com.read()
        print('Receiving...'+out)

提前致谢! :)

I would like to create a Python programm like a terminal to send some request with Pyserial.

But when I send a request like "dataid 60000 get value" it show me an error message like :
TypeError: unicode strings are not supported, please encode to bytes: 'dataid 60000 get value'

I tried to use .encode but no result..

See below my code :

#Modules
from base64 import encode
import serial

port = "COM5"
baud = 115200

#Serial port configuration
com = serial.Serial(port, baud, timeout=1)

if com.isOpen():
    print(com.name + ' is open...')

#Print output
while True:
    cmd = input("Enter command or 'exit':")
    if cmd == 'exit':
        com.close()
        exit()
    else:
        com.write(cmd)
        out = com.read()
        print('Receiving...'+out)

Thanks in advance ! :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只是一片海 2025-01-27 10:16:04

要通过串行/控制台端口发送命令,请使用:
com.write(cmd.encode(“ utf-8”)))

com.write(b“ string”)

这将您的输入编码为字节。

To send command over serial/console port, use:
com.write(cmd.encode("utf-8"))
or
com.write(b"string")

This encodes your input to bytes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文