希望用 Python 在命令行输出像 brew 那样的彩色文字,最简单的做法是?

2013-12-18 09:39:24 +08:00
 Livid
7214 次点击
所在节点    Python
19 条回复
RelativeLayout
2013-12-18 09:44:40 +08:00
Livid
2013-12-18 10:00:21 +08:00
Owenjia
2013-12-18 10:03:40 +08:00
直接输出 \[\033[前景色;背景色;控制代码m\] 这样的字符串就可以的~~
felix021
2013-12-18 10:04:04 +08:00
echo -e '\x1b[32mhello\x1b[0m'
dongsheng
2013-12-18 10:08:19 +08:00
把内容写在颜色和Reset之间就行了。

Default = '\033[0m'
Black = '\033[30m'
Red = '\033[31m'
Green = '\033[32m'
Yellow = '\033[33m'
Blue = '\033[34m'
Magenta = '\033[35m'
Cyan = '\033[36m'
White = '\033[37m'
Bold = '\033[1m'
Reverse = '\033[2m'
Blackbg = '\033[40m'
Redbg = '\033[41m'
Greenbg = '\033[42m'
Yellowbg = '\033[43m'
Bluebg = '\033[44m'
Magentabg = '\033[45m'
Cyanbg = '\033[46m'
Whitebg = '\033[47m'

Reset = '\033[0;0m'
TankyWoo
2013-12-18 10:08:45 +08:00
lovesky
2013-12-18 10:18:12 +08:00
clino
2013-12-18 10:20:45 +08:00
Shieffan
2013-12-18 10:36:07 +08:00
colorama
Mutoo
2013-12-18 11:18:01 +08:00
之前看 lua 简明教程的时候有看到过一个例子,后来去查了,这东西叫 Terminal control-codes

> Terminal (control-)codes are needed to give specific commands to your terminal. This can be related to switching colors or positioning the cursor, simply everything that can’t be done by the application itself.

不只是变换颜色,还能移动光标,清屏等各种操作。貌似只在 *nix 有效,windows无能。

http://old.mutoo.im/2013/02/lua-io-write-272j/
est
2013-12-18 12:19:48 +08:00
@Mutoo 其实Windows的cmd也可以加载ansi.sys之后就可以了。很sb的一个hack

http://blog.163.com/lovenet123@126/blog/static/35813760200994112242213/
ironblood
2013-12-18 13:23:54 +08:00
@Mutoo windows 下直接 telnet newsmth.net 就知道 win-cmd 能不能了。
dorentus
2013-12-18 14:10:07 +08:00
自己输出的话,用的就是上面大家提到的这个了:
http://en.wikipedia.org/wiki/ANSI_escape_code#Colors

Google keyword: ANSI color
dorentus
2013-12-18 14:11:48 +08:00
玩过当年各高校的命令行 BBS(比如楼上 iconblood 提到的 newsmth.net )的人应该都知道 :D
Mutoo
2013-12-18 14:46:22 +08:00
@ironblood
@est 我的意思是用 python或lua 写的跨平台脚本
dorentus
2013-12-18 15:04:44 +08:00
@Mutoo
Windows 自带的终端模拟器 cmd.exe 应该是支持在控制台输出颜色的,不过不支持 ANSI escape code,或者说得需要第三方扩展或者第三方终端模拟器才能支持脚本用 ANSI color escape code 输出颜色。
dawncold
2013-12-18 17:15:04 +08:00
@TankyWoo 这个回帖的css溢出了:)
TankyWoo
2013-12-18 17:52:23 +08:00
@dawncold 好像一直都有这个问题
est
2013-12-18 20:11:20 +08:00
@dorentus 看11楼的链接啊。。。支持ansi color的

再说一个很多人不知道的。其实WinRAR的注释也支持。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/93596

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX