You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

纯Python能否解除input函数的终端输入行长度限制?

解决方案

实现原理

Linux tty默认处于规范模式,线路规程会限制单行输入缓冲区最大为4095字节。Python标准库自带termios模块,可以直接在进程内修改终端属性,无需借助外部stty命令,运行程序时自动调整终端模式绕过该限制,程序退出前自动恢复原有终端配置。

完整修改后的代码

#!/usr/bin/env python3
import termios
import sys

def unbuffered_input(prompt=''):
    # 保存原有终端属性
    fd = sys.stdin.fileno()
    old_attr = termios.tcgetattr(fd)
    try:
        # 修改终端属性:关闭规范模式,保留回车转换行、回显、信号处理逻辑
        new_attr = old_attr[:]
        new_attr[3] &= ~termios.ICANON
        termios.tcsetattr(fd, termios.TCSANOW, new_attr)
        # 读取输入直到遇到换行符
        if prompt:
            print(prompt, end='', flush=True)
        buf = []
        while True:
            c = sys.stdin.read(1)
            if c == '\n':
                break
            buf.append(c)
        return ''.join(buf)
    finally:
        # 强制恢复原有终端属性,避免终端输入异常
        termios.tcsetattr(fd, termios.TCSANOW, old_attr)

s = unbuffered_input('Enter a long line please: ')
print('len(s) =', len(s))
print('end of s =', repr(s[-100:]))

注意事项

  • 该实现仅适用于Linux、macOS等类Unix系统,Windows系统需使用msvcrt模块做对应适配
  • 代码内置属性恢复逻辑,无论程序是否正常退出都不会破坏终端原有配置
  • 直接执行./dash2ink.py即可生效,无需配合额外的stty命令

内容的提问来源于stack exchange,提问作者FriendFX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 06:15:02