我有一段 python 代码,可以将 bash 历史记录中的条目注入(inject)到命令提示符中。
一切都很顺利,直到我切换到 Python 3。 现在德语元音变音似乎是错误的。
例如。
python3 console_test.py mööp
结果:
$ 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)
关于python - 通过 termios.TIOCSTI 注入(inject) unicode 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34632183/