Python has two prompts, ps1
and ps2
, which are found in the sys
module. As the sys
module documentation informs us, ps1
is the primary prompt and shows, by default, the usual >>>
, while ps2
is the secondary prompt and shows ...
by default.
You can customize the characters of the prompts by assigning a string to them. For example, you can change >>>
to ~~~
by running in a Python console:
>>> import sys
>>> sys.ps1 = '~~~ '
The string assigned to the prompts also accepts ANSI escape sequences which allow changing the color of the prompts. For example, you can use the following to change the primary prompt's color to red:
>>> import sys
>>> sys.ps1 = '\033[0;31m>>> \033[0m'
You can find more color codes in Prakasaka's GitHub Gist. Note that the actual displayed colors depend on the colors you use in your terminal's theme.
Changing the prompts the way described above will only affect the current Python console that the commands run in.
To make the changes persistent, you can create a Python startup file with the change you want to have in your prompt and assign it to the PYTHONSTARTUP
environment variable. You can do that as follows:
Create the file ~/.pythonstartup
:
nano ~/.pythonstartup
Note: You can actually name the file however you wish and put it where you want. Just make sure to use your custom file and path where required at the next steps.
Add the commands that customize your prompt to the file. Here I will add the commands for the red prompt that I used above:
import sys
sys.ps1 = '\033[0;31m>>> \033[0m'
Note: In some cases this format might cause issues, such as when trying to use the arrow keys to call commands from your history. If this happens, use this format instead:
import sys
sys.ps1 = '\x01\033[31m\x02>>> \x01\033[0m\x02'
Save and close the file by pressing Ctrl+O and then Ctrl+X.
Assuming you're using the Bash shell, append the following to your ~/.bashrc
file:
export PYTHONSTARTUP=$HOME/.pythonstartup
This command assigns the ~/.pythonstartup
file to the PYTHONSTARTUP
variable and exports it to the shell.
Now, if you open a new terminal with a Python console, you should have a nice red prompt!
References: