我有一段python代码,它将bash历史记录中的条目注入命令提示符。
在我切换到Python3之前,一切都运行得很好。现在,德国的Umlaute似乎错了。
例如:
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发布于 2016-01-06 21:16:15
我自己找到了答案,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)https://stackoverflow.com/questions/34632183
复制相似问题