2016-01-06 53 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)