Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse an existing sys.ps1 formatter in an IPython prompt?

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 $ '
like image 755
k_g Avatar asked Aug 12 '18 21:08

k_g


1 Answers

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:

enter image description here

like image 179
georgexsh Avatar answered Oct 29 '22 23:10

georgexsh