简体   繁体   中英

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.

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. However, when I print "\\[\\033[31m\\]" in python, the brackets show up on the screen.

How can I send the \\[ and \\] control characters to terminal from python?

(I've found that color libraries, such as colored , have the same problem)

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.

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.

In a Bash prompt vs in Python:

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

source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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