2016-01-06 52 views
1

我有一段python代码,它将条目从bash历史注入到命令提示符中。通过termios.TIOCSTI注入Unicode字符

一切工作完美,直到我切换到Python 3. 现在德国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 

回答

0

自己找到答案,Python3自动d使用文件系统编码来纠正参数,所以我必须在调用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)