Home Backend Development Python Tutorial Example analysis of Python outputting colored words under two systems

Example analysis of Python outputting colored words under two systems

May 12, 2017 am 10:21 AM
python

这篇文章主要介绍了在Windows和Linux中Python输出彩色文字的方法,通过设置彩色文字给大家更醒目的效果,文中给出了详细的介绍和示例代码,需要的朋友可以参考借鉴,下面来一起看看吧。

前言

最近在项目中需要输出彩色的文字来提醒用户,以前写过,但是只能在win上面运行。

今天搜了下看有没有在win和Linux上通用的输出彩色文字的模块,结果发现没有,,于是就自己弄了一个,分享下,以后用的时候翻翻博客,方便别人也方便自己。

win下输出彩色文字,网上有两种方法一种是用system执行命令来设置颜色,感觉还是不太好,用ctypes模块实现更好点。

linux下设置颜色,网上只找到了一种方法,下面不废话了,直接贴下代码:

示例代码


import platform
if 'Windows' in platform.system():
 import sys
 import ctypes
 stdInputHandle = -10
 stdOutputHandle = -11
 stdErrorHandle = -12
 foreGroundBLUE = 0x09
 foreGroundGREEN = 0x0a
 foreGroundRED = 0x0c
 foreGroundYELLOW = 0x0e
 stdOutHandle=ctypes.windll.kernel32.GetStdHandle(stdOutputHandle)
 def setCmdColor(color,handle=stdOutHandle):
 return ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
 def resetCmdColor():
 setCmdColor(foreGroundRED | foreGroundGREEN | foreGroundBLUE)
 def printBlue(msg):
 setCmdColor(foreGroundBLUE)
 sys.stdout.write(msg + '\n')
 resetCmdColor()
 def printGreen(msg):
 setCmdColor(foreGroundGREEN)
 sys.stdout.write(msg + '\n')
 resetCmdColor()
 def printRed(msg):
 setCmdColor(foreGroundRED)
 sys.stdout.write(msg + '\n')
 resetCmdColor()
 def printYellow(msg):
 setCmdColor(foreGroundYELLOW)
 sys.stdout.write(msg + '\n')
 resetCmdColor()
else:
 STYLE = {
 'fore':{
 'red': 31,
 'green': 32,
 'yellow': 33,
 'blue': 34,
 }
 }
 def UseStyle(msg, mode = '', fore = '', back = '40'):
 fore = '%s' % STYLE['fore'][fore] if STYLE['fore'].has_key(fore) else ''
 style = ';'.join([s for s in [mode, fore, back] if s])
 style = '\033[%sm' % style if style else ''
 end = '\033[%sm' % 0 if style else ''
 return '%s%s%s' % (style, msg, end)
 def printRed(msg):
 print UseStyle(msg,fore='red')
 def printGreen(msg):
 print UseStyle(msg,fore='green')
 def printYellow(msg):
 print UseStyle(msg,fore='yellow')
 def printBlue(msg):
 print UseStyle(msg,fore='blue')
Copy after login

效果图:

Windows:


C:\luan\lu4n.com-sqli>python
Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> from color import *
>>> printRed('Red')
Red
>>> printGreen('Green')
Green
>>> printYellow('Yellow')
Yellow
>>> printBlue('Blue')
Blue
>>> print 'http://lu4n.com/'
http://lu4n.com/
>>>
Copy after login

Linux:


[root@Luan ~]# nano test_color.py
[root@Luan ~]# python
Python 2.7.5 (default, Jun 17 2014, 18:11:42) 
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test_color import *
>>> printRed('Red')
Red
>>> printGreen('Green')
Green
>>>
Copy after login

用起来很容易,直接from color import *就可以用了,有4种常用颜色可以使用,分别写了4个函数

提示信息 printBlue

成功信息 printGreen

失败信息 printRed

警告信息 printYellow

bootstrap的几种颜色差不多,应该够用了。

总结

【相关推荐】

1. Python免费视频教程

2. Python面向对象视频教程

3. Python学习手册

The above is the detailed content of Example analysis of Python outputting colored words under two systems. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is Debian Strings worth using Is Debian Strings worth using Apr 02, 2025 am 08:24 AM

Regarding the choice of Debian system, this article will explore the advantages of Debian system and help you determine whether it is suitable for your needs. The image shows the missing search results related to DebianStrings, which prompts us to look at the Debian system from a broader perspective. Debian Community & Stability: Debian is known for its large and active open source community, which means you can easily access a large amount of documentation, tutorials, and community support to quickly resolve issues you encounter. The stability of the system is also a highlight of Debian, especially in the server environment, which is much more stable than other distributions. Debian vs. Ubuntu: Compared with Ubuntu, Debian

How is Debian Hadoop compatibility How is Debian Hadoop compatibility Apr 02, 2025 am 08:42 AM

DebianLinux is known for its stability and security and is widely used in server, development and desktop environments. While there is currently a lack of official instructions on direct compatibility with Debian and Hadoop, this article will guide you on how to deploy Hadoop on your Debian system. Debian system requirements: Before starting Hadoop configuration, please make sure that your Debian system meets the minimum operating requirements of Hadoop, which includes installing the necessary Java Runtime Environment (JRE) and Hadoop packages. Hadoop deployment steps: Download and unzip Hadoop: Download the Hadoop version you need from the official ApacheHadoop website and solve it

How safe is Golang logs in Debian How safe is Golang logs in Debian Apr 02, 2025 am 08:27 AM

As a safe and reliable programming language, Golang has built-in many features and third-party libraries to assist developers in building secure applications. When running Golang programs on Linux distributions such as Debian, log security mainly depends on the following key factors: 1. Efficient and secure log concurrent processing Golang provides multiple mechanisms to process concurrent log writing to avoid data competition: Channel: Use channels to safely transmit log information between multiple goroutines, effectively preventing concurrent write conflicts. Mutex: Ensure that only one goroutine is written to the log at the same time, but may reduce performance slightly. Lock-free queue (Lock-freeq)

Is Debian Strings compatible with multiple browsers Is Debian Strings compatible with multiple browsers Apr 02, 2025 am 08:30 AM

"DebianStrings" is not a standard term, and its specific meaning is still unclear. This article cannot directly comment on its browser compatibility. However, if "DebianStrings" refers to a web application running on a Debian system, its browser compatibility depends on the technical architecture of the application itself. Most modern web applications are committed to cross-browser compatibility. This relies on following web standards and using well-compatible front-end technologies (such as HTML, CSS, JavaScript) and back-end technologies (such as PHP, Python, Node.js, etc.). To ensure that the application is compatible with multiple browsers, developers often need to conduct cross-browser testing and use responsiveness

Does XML modification require programming? Does XML modification require programming? Apr 02, 2025 pm 06:51 PM

Modifying XML content requires programming, because it requires accurate finding of the target nodes to add, delete, modify and check. The programming language has corresponding libraries to process XML and provides APIs to perform safe, efficient and controllable operations like operating databases.

How to implement operations on Linux iptables linked lists in Golang? How to implement operations on Linux iptables linked lists in Golang? Apr 02, 2025 am 10:18 AM

Using Golang to implement Linux...

Is there any mobile app that can convert XML into PDF? Is there any mobile app that can convert XML into PDF? Apr 02, 2025 pm 08:54 PM

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages ​​and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

How to modify comment content in XML How to modify comment content in XML Apr 02, 2025 pm 06:15 PM

For small XML files, you can directly replace the annotation content with a text editor; for large files, it is recommended to use the XML parser to modify it to ensure efficiency and accuracy. Be careful when deleting XML comments, keeping comments usually helps code understanding and maintenance. Advanced tips provide Python sample code to modify comments using XML parser, but the specific implementation needs to be adjusted according to the XML library used. Pay attention to encoding issues when modifying XML files. It is recommended to use UTF-8 encoding and specify the encoding format.

See all articles