You need to enable JavaScript to run this app. Python命令行应用如何使用curses等库实现方向键编辑输入功能
优惠活动
大模型
产品
解决方案
定价
更多

Python命令行应用如何使用curses等库实现方向键编辑输入功能

可行实现方案

方案1:使用标准库readline(最简方案,零侵入原有代码)

这是最轻量的实现方式,Python内置的readline库(Windows系统需额外安装pyreadline3做兼容)导入后会自动接管input()的输入逻辑,原生支持方向键移动光标、编辑内容、历史命令回溯等功能,完全不需要修改原有业务逻辑。
代码示例:

import readline
# Windows系统需先执行 pip install pyreadline3 完成兼容

while True:
    command = input("command >")

    if command == "say_hello":
        print("Hello")
    elif command == "exit":
        exit()
    else:
        print("Undefined command")

如果需要自定义命令补全、历史命令持久化也可以基于readline扩展,完全满足基础交互需求。

方案2:使用curses库手动实现(自定义程度最高)

如果需要完全自定义输入交互逻辑,可以用curses库实现,示例实现如下:

import curses

def main(stdscr):
    # 初始化curses基础设置
    curses.echo()
    curses.curs_set(1)
    prompt = "command >"
    
    while True:
        stdscr.addstr(prompt)
        stdscr.refresh()
        buf = []
        cursor_pos = 0
        
        while True:
            key = stdscr.getch()
            # 回车键提交输入
            if key == ord('\n'):
                stdscr.addch('\n')
                command = ''.join(buf)
                # 执行业务逻辑
                if command == "say_hello":
                    stdscr.addstr("Hello\n")
                elif command == "exit":
                    return
                else:
                    stdscr.addstr("Undefined command\n")
                stdscr.refresh()
                break
            # 退格键删除字符
            elif key == curses.KEY_BACKSPACE or key == 127:
                if cursor_pos > 0:
                    cursor_pos -= 1
                    buf.pop(cursor_pos)
                    # 重绘当前输入行
                    stdscr.move(stdscr.getyx()[0], len(prompt))
                    stdscr.clrtoeol()
                    stdscr.addstr(''.join(buf))
                    stdscr.move(stdscr.getyx()[0], len(prompt) + cursor_pos)
            # 左方向键移动光标
            elif key == curses.KEY_LEFT:
                if cursor_pos > 0:
                    cursor_pos -= 1
                    stdscr.move(stdscr.getyx()[0], len(prompt) + cursor_pos)
            # 右方向键移动光标
            elif key == curses.KEY_RIGHT:
                if cursor_pos < len(buf):
                    cursor_pos += 1
                    stdscr.move(stdscr.getyx()[0], len(prompt) + cursor_pos)
            # 普通字符输入
            elif 32 <= key <= 126:
                buf.insert(cursor_pos, chr(key))
                cursor_pos += 1
                # 重绘当前输入行
                stdscr.move(stdscr.getyx()[0], len(prompt))
                stdscr.addstr(''.join(buf))
                stdscr.move(stdscr.getyx()[0], len(prompt) + cursor_pos)
            stdscr.refresh()

if __name__ == "__main__":
    curses.wrapper(main)

该实现支持左右方向键移动光标、任意位置插入删除字符、回车提交的基础逻辑,可以按需扩展快捷键、高亮、补全等更多交互功能。

方案3:使用第三方库prompt_toolkit(功能最丰富)

如果需要支持语法高亮、命令自动补全、多行输入等更复杂的交互能力,可以使用专门的命令行交互库prompt_toolkit,实现更简单,效果更完善。
首先安装依赖:pip install prompt_toolkit
代码示例:

from prompt_toolkit import prompt

while True:
    command = prompt("command >")

    if command == "say_hello":
        print("Hello")
    elif command == "exit":
        exit()
    else:
        print("Undefined command")

prompt_toolkit默认就支持方向键编辑、历史命令、自动补全等功能,非常适合开发类metasploit的专业控制台工具。

内容的提问来源于stack exchange,提问作者Muhammed Özen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 10:15:00