Search code examples
pythonipythonprompt

how to show current directory in ipython prompt


Is there is way to show the current directory in IPython prompt?

Instead of this:
In [1]:

Something like this:
In<~/user/src/proj1>[1]:

Solution

  • Assuming you're interested in configuring this for all subsequent invocations of ipython, run the following (in a traditional shell, like bash :) ). It appends to your default ipython configuration, creating it if necessary. The last line of the configuration file will also automatically make all the executables in your $PATH available to simply run in python, which you probably also want if you're asking about cwd in the prompt. So you can run them without a ! prefix. Tested with IPython 7.18.1.

    mkdir -p ~/.ipython/profile_default
    cat >> ~/.ipython/profile_default/ipython_config.py <<EOF
    
    from IPython.terminal.prompts import Prompts, Token
    import os
    
    class MyPrompt(Prompts):
        def cwd(self):
            cwd = os.getcwd()
            if cwd.startswith(os.environ['HOME']):
                cwd = cwd.replace(os.environ['HOME'], '~')
                cwd_list = cwd.split('/')
                for i,v in enumerate(cwd_list):
                    if i not in (1,len(cwd_list)-1): #not last and first after ~
                        cwd_list[i] = cwd_list[i][0] #abbreviate
                cwd = '/'.join(cwd_list)
            return cwd
    
        def in_prompt_tokens(self, cli=None):
            return [
                    (Token.Prompt, 'In ['),
                    (Token.PromptNum, str(self.shell.execution_count)),
                    (Token.Prompt, '] '),
                    (Token, self.cwd()),
                    (Token.Prompt, ': ')]
    
    c.TerminalInteractiveShell.prompts_class = MyPrompt
    c.InteractiveShellApp.exec_lines = ['%rehashx']
    EOF
    

    (c.PromptManager only works in older versions of ipython.)