Ipython as Main Terminal

1 minute read

I frequently use Python code snippets to manipulate data in files, which is why I have decided to run IPython as one of my shells. While it may be a little confusing at first, it is possible to set up custom configurations, which should definitely help to use ipython as a main shell :-)

If you have ipython already installed create your profile:

1ipython profile create
2
3# default profile will be created i your home directory path
4~/.ipython/profile_default

Inside this path direcotry startup folder is created, ipython will execute each of the files frim this location during the launch. And this is all what we need to know to create custom prompts or run some code on ipython startup.

 1from IPython.terminal.prompts import Prompts, Token
 2from pathlib import Path
 3from platform import python_version
 4import os
 5import subprocess
 6
 7def git_branch():
 8    try:
 9        return (
10            subprocess.check_output(
11                "git branch --show-current", shell=True, stderr=subprocess.DEVNULL
12            )
13            .decode("utf-8")
14            .replace("\n", "")
15        )
16    except BaseException:
17        return ""
18
19
20class Custom_Prompt(Prompts):
21    def in_prompt_tokens(self, cli=None):
22        return [
23            (Token.Prompt, "ipython"),
24            (Token, " "),
25            (Token.Name.Entity, Path().absolute().stem),
26            (Token, " "),
27            (Token.Generic.Subheading, "↪"),
28            (Token.Generic.Subheading, git_branch()),
29            (Token, " "),
30            (
31                Token.Prompt
32                if self.shell.last_execution_succeeded
33                else Token.Generic.Error,
34                "❯ ",
35            ),
36        ]
37
38    def out_prompt_tokens(self, cli=None):
39        return []
40
41ip = get_ipython()
42ip.prompts = Custom_Prompt(ip)

Finally we have our custom prompt, to run bash commands in contrast to a regular Linux shell, start shell command with a !.