简体   繁体   English

如何从python打印\\ [和\\]到终端?

[英]How to print \[ and \] to terminal from python?

I am able to print ANSI color codes from python to the terminal using code such as print "\\033[31m red text \\033[0m" , which prints "red text" in red. 我能够使用诸如print "\\033[31m red text \\033[0m"代码将python的ANSI颜色代码从python打印到终端,该命令以红色打印“ red text”。

However, when wrapping text, the terminal still counts the invisible control characters, so the text wraps incorrectly, acting as if the line is longer than it actually is. 但是,在换行时,终端仍会计算不可见的控制字符,因此文本会不正确地换行,就好像行比实际的要长。 Reverse-i-search also acts weird, displaying text that does not match up with what is actually under the cursor. 反向搜索也很奇怪,显示的文本与光标下的实际内容不匹配。

The following link (and others) https://wiki.archlinux.org/index.php/Color_Bash_Prompt#Regular_user_2 seems to indicate that I need to wrap colors codes in \\[ and \\] so that terminal can place the cursor correctly on the screen. 以下链接(和其他链接) https://wiki.archlinux.org/index.php/Color_Bash_Prompt#Regular_user_2似乎表明我需要将颜色代码包装在\\[\\]以便终端可以将光标正确放置在屏幕。 However, when I print "\\[\\033[31m\\]" in python, the brackets show up on the screen. 但是,当我在python中print "\\[\\033[31m\\]"时,括号会显示在屏幕上。

How can I send the \\[ and \\] control characters to terminal from python? 如何从python将\\[\\]控制字符发送到终端?

(I've found that color libraries, such as colored , have the same problem) (我发现颜色库(例如colored )有相同的问题)

Do not use [ ] around your color codes. 请勿在颜色代码周围使用[]。 just create variables such as below. 只需创建以下变量即可。

red = '\033[31m'
print red 

Based on comment by @chepner - My problem involved modifying the PS1 variable in terminal to get a colored prompt. 基于@chepner的评论-我的问题涉及修改终端中的PS1变量以获得彩色提示。

Directly printing \\[ and \\] from python showed those characters on the screen, but when passed to PS1 , the characters were invisible and the colored text displayed correctly and wrapped correctly on the screen. 从python直接打印\\[\\]可以在屏幕上显示这些字符,但是当传递给PS1 ,这些字符是不可见的,彩色文本可以正确显示并正确包装在屏幕上。

In a Bash prompt vs in Python: 在Bash提示与Python中:

  • \\[ == '\\001' \\[ == '\\001'
  • \\] == '\\002' \\] == '\\002'

source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM