使用ANSI转义码构建你自己的命令行 (2016)
Build your own Command Line with ANSI escape codes (2016)

原始链接: https://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html

这篇文章探讨了如何使用 ANSI 转义码直接从命令行程序控制终端行为——这些特殊代码指示终端改变文本颜色、移动光标和清除屏幕部分内容。虽然 Readline 和 Python Prompt Toolkit 等库简化了这个过程,但理解底层代码可以实现更大的自定义性。 核心概念是将这些代码(例如,`\u001b[31m` 用于红色文本,`\u001b[0m` 用于重置)发送到程序输出中。文章通过 Python 示例演示了这一点,从基本的文本着色开始,逐步进展到创建动态元素,如加载进度指示器和简陋的命令行界面。构建这个命令行涉及处理用户输入、光标移动以进行编辑以及清除行以进行更新。 作者 Haoyi 强调了创建更丰富、更具交互性的命令行体验的潜力,超越了传统库所能提供的功能——例如语法高亮和高级文本选择。他强调,虽然实现这些功能需要付出努力,但掌握 ANSI 转义码可以解锁强大的可能性,从而构建自定义工具和界面。最终,直接的终端控制使开发者能够创建具有与桌面环境相媲美功能的创新命令行应用程序。

黑客新闻 新 | 过去 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 使用 ANSI 转义码构建你自己的命令行 (2016) (lihaoyi.com) 5 分,vinhnx 发表于 1 小时前 | 隐藏 | 过去 | 收藏 | 讨论 帮助 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索:
相关文章

原文

Everyone is used to programs printing out output in a terminal that scrolls as new text appears, but that's not all your can do: your program can color your text, move the cursor up, down, left or right, or clear portions of the screen if you are going to re-print them later. This is what lets programs like Git implement its dynamic progress indicators, and Vim or Bash implement their editors that let you modify already-displayed text without scrolling the terminal.

There are libraries like Readline, JLine, or the Python Prompt Toolkit that help you do this in various programming languages, but you can also do it yourself. This post will explore the basics of how you can control the terminal from any command-line program, with examples in Python, and how your own code can directly make use of all the special features the terminal has to offer.


About the Author: Haoyi is a software engineer, and the author of many open-source Scala tools such as the Ammonite REPL and the Mill Build Tool. If you enjoyed the contents on this blog, you may also enjoy Haoyi's book Hands-on Scala Programming


The way that most programs interact with the Unix terminal is through ANSI escape codes. These are special codes that your program can print in order to give the terminal instructions. Various terminals support different subsets of these codes, and it's difficult to find a "authoritative" list of what every code does. Wikipedia has a reasonable listing of them, as do many other sites.

Nevertheless, it's possible to write programs that make use of ANSI escape codes, and at least will work on common Unix systems like Ubuntu or OS-X (though not Windows, which I won't cover here and is its own adventure!). This post will explore the basics of what Ansi escape codes exist, and demonstrate how to use them to write your own interactive command-line from first principles:

To begin with, let's start off with a plain-old vanilla Python prompt:

And get started!

Rich Text