简体   繁体   English

Python串行命令发送CTRL + L

[英]Python serial commands to send CTRL+ L

I have a customer display, that's connected to serial port. 我有一个客户显示器,它已连接到串行端口。 I am using a windows machine for this. 我为此使用Windows机器。

图片

I want to send Ctrl + L to clear the display of customer display, but I cannot find a solution that helps me. 我想发送Ctrl + L来清除客户显示的显示,但是找不到能帮助我的解决方案。 Basically I wish to send Ctrl +'any commands' in future. 基本上,我希望以后发送Ctrl +'any命令'。

In command Prompt I can use " Ctrl + L " to clear the existing display and display the text. 在命令提示符下,我可以使用“ Ctrl + L ”清除现有显示并显示文本。 The following is the command that gets displayed in prompt 以下是在提示符下显示的命令

echo ^LDisplay me > COMX // ^L is actually CTRL + L 

The above will output as , 上面的输出为

  1. Clears the display. 清除显示。

  2. Displays "Display me" 显示“显示我”

Now I am trying to achieve the same thing using Python serial connector. 现在,我正在尝试使用Python串行连接器实现相同的目的。

import serial
ser = Serial ('COM5',timeout=2)
ser.write("\x0C") # equivalent to ctrl+L

This does not work at all. 这根本不起作用。 I get error as ` 我收到错误信息为

Exception in serial connection: unicode strings are not supported, please encode to bytes:'\\x03' 串行连接中的异常:不支持unicode字符串,请编码为字节:'\\ x03'

However if I try the following for normal texts, it works perfectly, 但是,如果我尝试以下常规文本,则效果很好,

ser.write("Display me".encode()

This displays "Display me" in the customer display. 这将在客户显示中显示“显示我”。

I tried to use ser.write("\\x0C".encode()) but I get no output. 我尝试使用ser.write("\\x0C".encode())但没有输出。

I get error as 我得到错误

Exception in serial connection: unicode strings are not supported, please encode to bytes:'\\x1fc\\x00' 串行连接中的异常:不支持unicode字符串,请编码为字节:'\\ x1fc \\ x00'

I would appreciate any suggestions, improvements and help to solve this. 我将不胜感激任何建议,改进和帮助解决此问题。 Thanks. 谢谢。

To encode a Ctrl + L as bytes in Python3, you should use: 要将Ctrl + L编码为Python3中的字节,应使用:

b'\x0c'

Why? 为什么?

Ascii control characters are encoded as their position in the alphabet, so Ctrl + C , since it is the third letter of the alphabet, encoded as a hex string, would be \\x03 . Ascii控制字符被编码为它们在字母表中的位置,因此Ctrl + C (因为它是字母表的第三个字母,被编码为十六进制字符串)将为\\x03 Similarly, Ctrl + L would \\x0c (hex C is decimal 12). 同样, Ctrl + L将为\\x0c (十六进制C为十进制12)。

In python 3 to get bytes, you can pre-pend the string with a b . 在python 3中获取字节,您可以在字符串前加上b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM