My computer is configured to Windows 11 , Python 版本是 Anaconda python 3.9 ,This problem before Windows 10, Python 3.7 Should be can emersion.
In this thank you by https://www.cnblogs.com/pylemon/archive/2011/06/11/2078456.html 帶來的靈感,Hope to be able to share experience for everyone.
當然,My solution is not necessarily the best,If any errors or bosses to see more simple way to welcome to correct me.
(文章可能有點水,Feel more nonsense from"How to support virtual terminal"開始看)
最開始,I'm going to write a small file data processing tools and sharing,Due to the performance requirements of mistakes,I was going to use C++ 追求性能(After found this with something once a week C++ Every time the most can speed up15秒),The result is because of the need to type in Chinese at the same time the file name and useUTF-8
Coding the matter has been on pit,(2022In Microsoft connectutf-8都沒搞明白),So still intends to adopt Python + Pyinstaller .
Because I don't want to make too much trouble,所以就沒有使用 GUI 圖形界面.But it's too boring,I want the console has a different color,At least look better.I remembered to see before colorama 庫,上次在 IDLE Run out of a pile of garbage characters,But I think this is probably the most IDLE 的問題吧.然而,The development of things far beyond my expectation,我在“The console virtual terminal sequence”上
Virtual console terminal sequence is such a thing(以下內容是 Microsoft Windows 官方的文檔):
Virtual terminal sequence is to control the character sequence,Can be written to the output stream control cursor movement、The console color and other operating. In the input stream can also receive sequence,In response to the output stream query information sequence,Or in setting appropriate mode as the user input code.
可以使用 GetConsoleMode 和 SetConsoleMode Function configure this behavior . At the end of this document contains advice to enable virtual terminal behavior method of sample.
The following sequence of actions based on VT100 And derived a terminal emulator technology,尤其是 xterm 終端仿真器. Detailed information about the terminal sequence,請訪問 http://vt100.net 和 http://invisible-island.net/xterm/ctlseqs/ctlseqs.html.
I believe you also found Microsoft to write the document(Especially the Chinese version)True to write a little shady,And the entire page to a bunch of links don't know where to go looking for.
簡而言之,Virtual terminal is a series of control character sequences,它們都以ESC
開始( ASCII Coding for decimal 27 ,八進制 33 ,十六進制 1B ,因此在 Python 中可以寫作\033
或\x1b
),But the most with a[
或(
,Coupled with the core digital,Eventually one letter.
在此,We don't discuss so much,I just want to color,Then according to the document,Obviously we should look for“文本格式”,But Microsoft no other bloggers summary of good,搜一下Python 控制台彩色輸出
Results a handful.
But we don't need to know so much,We only need a library——
先進行一下pip install colorama
.
如果你有IPython
,You can try this code:
from colorama import Fore, Back, Style
print(Fore.RED + "This is a font color red" + Back.CYAN + "This paragraph and cyan background"
+ Style.BRIGHT + "This a brighter" + Style.RESET_ALL + "This period of what style is gone")
結果大概是這樣(挺不錯的):
不過,Colorama並不是本文的重點,Online tutorials and search a handful,但是問題就在於:
Colorama 靠什麼實現?
我們注意到Colorama
Style can be directly with the string+
運算,This is not because it has carried on the overloaded,But because it is a string of a string.不信看看:
In [1]: from colorama import Fore, Back, Style
In [2]: Fore.RED
Out[2]: '\x1b[31m'
In [3]: type(Fore.RED)
Out[3]: str
In [4]: Fore.RED + "This is a font color red" + Back.CYAN + "This paragraph and cyan background"
...: + Style.BRIGHT + "This a brighter" + Style.RESET_ALL + "This period of what style is gone"
Out[4]: '\x1b[31mThis is a font color red\x1b[46mThis paragraph and cyan background\x1b[1mThis a brighter\x1b[0mThis period of what style is gone'
對 C++ The console must be further operation experience must know, C++ For a long time are called windows.h
內的 API 來實現的,But now these complex grammar have been Microsoft Suggested by the,Also use virtual terminal sequence.(It not only can reduce to a certain extent或升高代碼的復雜度,Can also better cross-platform support(注:這一點目前還不清楚,But the trend is that).)
那麼,What's the problem with by virtual terminal sequence?當然有.
I'm doingColorama
An example of usingIPython
而不是Python
自帶的 shell ,It is not only becauseIPython
Make the code look better、操作更方便,更主要是因為:
用 Python 自帶的 Shell 它根本就不行!!!
不信我們試試:
打開默認的 cmd 或 Powershell ,輸入"Python",Enter the code just now again:
>>> from colorama import Fore, Back, Style
>>> print(Fore.RED + "This is a font color red" + Back.CYAN + "This paragraph and cyan background" + Style.BRIGHT + "This a brighter" + Style.RESET_ALL + "This period of what style is gone")
Then you will be surprised to find that the output is such a:
看到問題了嗎?ESCOutput character is stil, cmd 下的 Python Don't support virtual terminal!
Win11 有個“終端”軟件,Use it to try:
(The zha, nice???)
再用 VS Code 試試.
Don't figure out,也可以支持.
然而,If we directly use the command line to run .py File or simply double-click to open,We will find that it is also does not support the color.
上面說過了,“終端”軟件是支持的,而 cmd 和 Powershell 是不支持的.
PyInstaller Because of the disguised pack a Python The virtual machine in,所以生成的 .exe 's support of the file with the open mode is exactly the same.
什麼原因?
Actually very simple reason nature:Whether they have been supporting virtual terminal sequence.
Windows 自帶的 cmd 和 powershell It is not support virtual terminal sequence. Python Itself will not automatically enabled.因此,兩者一起,就無法正常輸出了.
但是,“終端”Software default open support for virtual terminal sequence,而 IPython Itself has been kept in use the console advanced skills,So to some extent is also built in.
Actually this time Microsoft Document is good,Give an example:
https://docs.microsoft.com/zh-cn/windows/console/console-virtual-terminal-sequences#example-of-enabling-virtual-terminal-processing
If you are too lazy to turn problems also not,但是有一個小小的問題:它好像是 C Language!(
好,So now you can write a C-Extension 或者用 Cython Take it in.
To tell the truth this method should be all right,But we see if there are any better writing.(The above code clearly only for Windows ,And for the trouble、Little experience in development or you want to use Python Events end not very friendly.)
那麼,就沒有辦法了嗎?其實有,而且還非常簡單——
同樣地,先安裝庫 pip install console
官方文檔在這:https://pypi.org/project/console/
(順便說一句:安裝了 console 就基本不需要 colorama 了, console 的支持非常全面,當然,Module loading time is long.前面介紹 colorama Just because its most advertised,And few people pointed out that its fatal weakness.)
再來試試,這次換個寫法:
from console import fg, bg, fx
print(fg.red + "This is a font color red" + bg.cyan + "This paragraph and cyan background" + fx.blink + "This a brighter" + fx.end + " This period of what style is gone")
其實你會發現,It can be a smooth transition in the past.而且console
Provides a more comprehensive support,建議試一下.
We will use the original cmd + Python + colorama 的配置,Just add a import console
,輸入:
import console
from colorama import Fore, Back, Style
print(Fore.RED + "This is a font color red" + Back.CYAN + "This paragraph and cyan background" + Style.BRIGHT + "這 A brighter" + Style.RESET_ALL + "This period of what style is gone")
然後你就會發現:“console I post all useless,Zha support again?”運行效果(Because the figure,我就偷個懶,Make a copy of the previous):
為什麼會這樣?(Do the shallow level of parsing here):
找一下console
的源碼:
在__init__.py
裡有:
# detection is performed if not explicitly disabled
if (_env.PY_CONSOLE_AUTODETECT.value is None or
_env.PY_CONSOLE_AUTODETECT.truthy):
# detect palette, other modules are dependent
from .detection import init as _init
term_level = _init(using_terminfo=using_terminfo)
而且 if Expression in normal environment is generallyTrue
,所以就會調用.detection.init
.
再繼續看看detection.py
:
... It seems I overestimate myself,Interested can go to study,大概是env
The reason why the library.
總之,這一機制使得console
Once the library is called can directly provide virtual terminal support.
你可以將colorama
轉換為console
,也可以不轉.
最後一個問題:那麼,If the software need toPyInstaller
打包呢?
如果你用 console 用到底,The last is not what great things(所以我建議還是用console
):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from console import fg, bg, fx # type: ignore
print(fg.red + "This is a font color red" + bg.cyan + "This paragraph and cyan background" + fx.blink
+ "This a brighter" + fx.end + "This period of what style is gone")
input("按回車鍵退出:")
打包並運行,發現結果正常.
但是:如果你用 colorama ,And really just call import console
,那麼:
由於(大概) PyInstaller Packaging in order to prevent the file is too large,Will get rid of with less than library and function,所以就會有問題.
把代碼改一下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from colorama import Fore, Back, Style # type: ignore
import console # type: ignore
print(Fore.RED + "This is a font color red" + Back.CYAN + "This paragraph and cyan background"
+ Style.BRIGHT + "This a brighter" + Style.RESET_ALL + "This period of what style is gone")
input("按回車鍵退出:")
發現運行正常,打包一下:
翻車了,This is normal,But before that a hint say missing console.detection
,I added a lineimport console.detection
就好了,總之 Python A lot of things is the metaphysics.Have encountered the same problem can draw lessons from the.
colorama
,改用console
好了,This is the main content of the,If feel useful or solve the problem,給作者點個贊吧!