python - 通过 termios.TIOCSTI 注入(inject) unicode 字符

标签 python python-3.x unicode console termios

我有一段 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/

相关文章:

python - 打印函数中 "end"参数的作用是什么?

python - scikit随机森林sample_weights的使用

python-3.x - 在 Pandas 数据框行中仅保留第一组非 nan 值

android - 为什么 TextView 在底行显示 unicode 右箭头 (\u2192)?

mysql - UTF-8字符有问题;我看到的不是我存储的

python - Selenium firefox 仅在通过 Windows 任务计划程序运行时无法加载

python - np.linalg.qr(A) 或 scipy.linalg.orth(A) 用于查找正交基(python)

python-3.x - 如何在 Python3 中从 Éphémère 到 Éphémère?

python - sklearn cross_val_score 的准确性低于手动交叉验证

python - 从 SQL Server 到 Postgres 的 '😕' 上的 SQLAlchemy UnicodeEncodeError