Python和StackOverflow都是新手,我想要一些帮助。我想在Python中打印颜色并使用Google搜索但运气不佳:(我每次都感到困惑,没有一个工作。这是我输入的代码。
answer = input ("Wanna go explore? OPTIONS : Yes or No")
if answer == "no":
print("Awww, come on, don't be like that, lets go!")
elif answer == "yes":
print ("Great! Lets go!")
else:
print("Whats that? I couldn't hear you!")
现在,我希望OPTIONS为绿色,是蓝色,无红色。如何实现这一目标?
如果你想在IDLE shell中打印颜色,使用ASCII转义码的答案对你没有帮助,因为它没有实现这个功能。
有一个特定于IDLE的hack,它允许你直接写入它的PyShell
对象并指定IDLE已经定义的文本标签,例如"STRING"
,它默认显示为绿色。
import sys
try:
shell = sys.stdout.shell
except AttributeError:
raise RuntimeError("you must run this program in IDLE")
shell.write("Wanna go explore? ","KEYWORD")
shell.write("OPTIONS","STRING")
shell.write(" : ","KEYWORD")
shell.write("Yes","DEFINITION")
shell.write(" or ","KEYWORD")
shell.write("No","COMMENT")
answer = input()
在IDLE中运行时将导致此提示:
以下是所有有效标签的列表:
print("here are all the valid tags:\n")
valid_tags = ('SYNC', 'stdin', 'BUILTIN', 'STRING', 'console', 'COMMENT', 'stdout',
'TODO','stderr', 'hit', 'DEFINITION', 'KEYWORD', 'ERROR', 'sel')
for tag in valid_tags:
shell.write(tag+"\n",tag)
请注意,'sel'
是特殊的,它表示所选的文本,因此一旦点击其他内容,它将被取消选中。它也可以用来启动一些选择复制的文本。
看看curses
模块。这将取代print
语句,让您完全控制屏幕上的文本定位和属性。
如果您只是想要一个非常简单直接的方式在终端中打印ansi颜色,您可以查看ansicolor package module:
通过pip安装
$ pip install ansicolors
用法片段
from colors import red, green, blue
print red('This is red')
print green('This is green')
print blue('This is blue')
from colors import color
for i in range(256):
print color('Color #%d' % i, fg=i)
关于pip的说明
pip是一个python包管理器。如果您没有安装pip
,可以使用easy_install pip
安装它
如果你发现你没有easy_install
,那就下载:http://peak.telecommunity.com/dist/ez_setup.py并做:
python ez_setup.py
easy_install pip
Windows命令shell的颜色
上面的ansi颜色在windows命令shell中不适合你。试着看看这个activestate code snippet
如果您正在使用支持ANSI转义序列的终端和/或shell,则以下内容应该有效:
print("Blah blah \033[0;32mthis part will be green\033[00m blah blah.")
print("Blah blah \033[0;31mthis part will be red\033[00m blah blah.")
我可以确认它在Linux上的bash
中有效。有关更多详细信息,请参阅Wikipedia page on ANSI escape codes,包括描述不同字符序列/值的影响的综合表。我不主张这是一个规范的解决方案,但它可能足以满足您的目的。
如果要打印到彩色终端,则必须使用您正在使用的终端的转义码。对于unix / linux系统,您可以使用curses
模块 - 或者直接使用bash color codes作为输出字符串的一部分。根据this question,在Windows中似乎没有一种简单的方法可以做到这一点。
Clint(命令行界面工具)是我用过的一个很好的库。它是一个多功能库,可用于与终端有关的任何事情。那里有颜色,是/否提示,进度条等功能。
使用Client进行彩色输出如下所示:
>>> from clint.textui import colored, puts
>>> puts(colored.red('red text'))
red text