Python 通过termios.TIOCSTI注入unicode字符
我有一段python代码,它将bash历史记录中的条目注入命令提示符 在我切换到Python3之前,一切都很顺利。 现在德国乌姆劳特似乎错了 例如 结果:Python 通过termios.TIOCSTI注入unicode字符,python,python-3.x,unicode,console,termios,Python,Python 3.x,Unicode,Console,Termios,我有一段python代码,它将bash历史记录中的条目注入命令提示符 在我切换到Python3之前,一切都很顺利。 现在德国乌姆劳特似乎错了 例如 结果: $ m� 以下是相关代码: import fcntl import sys import termios command = sys.argv[1] fd = sys.stdin.fileno() old = termios.tcgetattr(fd) new = termios.tcgetattr(fd) new[3] = new[3
$ m�
以下是相关代码:
import fcntl
import sys
import termios
command = sys.argv[1]
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~termios.ECHO # disable echo
termios.tcsetattr(fd, termios.TCSANOW, new)
for c in command:
fcntl.ioctl(fd, termios.TIOCSTI, c)
termios.tcsetattr(fd, termios.TCSANOW, old)
我尝试将输入编码为utf-8,但结果是:
OSError: [Errno 14] Bad address
我自己找到了答案,Python3使用文件系统编码自动解码参数,因此在调用ioctl之前,我必须将其反转:
import fcntl
import sys
import termios
import struct
import os
command = sys.argv[1]
if sys.version_info >= (3,):
# reverse the automatic encoding and pack into a list of bytes
command = (struct.pack('B', c) for c in os.fsencode(command))
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~termios.ECHO # disable echo
termios.tcsetattr(fd, termios.TCSANOW, new)
for c in command:
fcntl.ioctl(fd, termios.TIOCSTI, c)
termios.tcsetattr(fd, termios.TCSANOW, old)
import fcntl
import sys
import termios
import struct
import os
command = sys.argv[1]
if sys.version_info >= (3,):
# reverse the automatic encoding and pack into a list of bytes
command = (struct.pack('B', c) for c in os.fsencode(command))
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~termios.ECHO # disable echo
termios.tcsetattr(fd, termios.TCSANOW, new)
for c in command:
fcntl.ioctl(fd, termios.TIOCSTI, c)
termios.tcsetattr(fd, termios.TCSANOW, old)