I have a function f
that produces a PS1 prompt for python, set as such:
sys.ps1 = f
Following the instructions in the documentation, I ended up with the following:
from IPython.terminal.prompts import Prompts, Token
from IPython import get_ipython
class MyPrompt(Prompts):
def in_prompt_tokens(self, cli=None):
return [(Token, f())]
ipython = get_ipython()
ipython.prompts = MyPrompt(ipython)
However, this doesn't work, since f
returns a string with color codes, which python
prints directly to the terminal, leading to a colorful prompt, while ipython
prints escaped, leading to a bunch of escape codes.
I know I can reconfigure f
to use ipython's internal coloring scheme, but is there a way to force it to use the shell's color codes without escaping them?
While f
is a function that takes into account information about its environment, here's an implementation that shows its output in one situation (it uses colorama behind the hood, so this is just the ouptut on unix systems).
def f():
return '\x01\x1b[1m\x1b[33m\x02kavi\x01\x1b[0m\x02 \x01\x1b[38;5;214m\x02/home\x01\x1b[38;5;82m\x02/kavi\x01\x1b[38;5;28m\x02\x01\x1b[0m\x02 \x01\x1b[38;5;38m\x02master\x01\x1b[0m\x02 $ '
IPython shell is built on prompt-toolkit, its style could be overridden with TerminalInteractiveShell._style
:
from prompt_toolkit.styles import style_from_dict
from IPython.terminal.prompts import Prompts, Token
from IPython import get_ipython
style = style_from_dict({
Token.User: '#f8ea6c',
Token.Path_1: '#f08d24',
Token.Path_2: '#67f72f',
Token.Git_branch: '#1cafce',
Token.Pound: '#000',
})
class MyPrompt(Prompts):
def in_prompt_tokens(self, cli=None):
return [
(Token.User, 'kavi '),
(Token.Path_1, '/home'),
(Token.Path_2, '/kavi'),
(Token.Git_branch, ' master '),
(Token.Dollar, '$ '),
]
ipython = get_ipython()
ipython.prompts = MyPrompt(ipython)
ipython._style = style
run it with ipython -i colored_ipy_prompt.py
:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With