Change Python interactive prompt “>>>”

2019-03-23 08:05发布

This is probably a silly question, and I'll probably end up deleting it once I figure it out, but I swear I recall reading, in the Python 3.5 docs, how to change the >>> on the Python interactive prompt, such as how calling help() will change it to help>. But for some reason, when I've gone back to try and remember, I just can't find the instructions to it. Does anyone know if this is possible, or am I just imagining things?

Thanks

2条回答
Emotional °昔
2楼-- · 2019-03-23 08:09

You remember correctly.

It's in the sys module (sys.ps1 & sys.ps2):

Strings specifying the primary and secondary prompt of the interpreter. These are only defined if the interpreter is in interactive mode. Their initial values in this case are '>>> ' and '... '. If a non-string object is assigned to either variable, its str() is re-evaluated each time the interpreter prepares to read a new interactive command; this can be used to implement a dynamic prompt.

For example:

   >>> import sys
   >>> sys.ps1 = "3.5>>> "
   3.5>>> sys.ps2 = "3.5... "
   3.5>>>
查看更多
迷人小祖宗
3楼-- · 2019-03-23 08:25

It's great to set it to either:

  1. a color for better visual aspect
  2. a blank or space for easier copy/paste operations

Paste this into your bash shell:

tee ~/.pyrc <<EOF
#!/usr/bin/env python3
import sys
sys.ps1='\x1b[1;49;33m>>>\x1b[0m '  # bright yellow
sys.ps2='\x1b[1;49;31m...\x1b[0m '  # bright red
#sys.ps1='\x1b[33m>>>\x1b[0m '      # dark yellow
#sys.ps2='\x1b[31m...\x1b[0m '      # dark red

# For easy copy/paste of proper code, use a blank or space:
#sys.ps1=' '
#sys.ps2=' '
EOF

# Then do this:
chmod 755 ~/.pyrc

Finally add this line to your ~/.bash_profile:

export PYTHONSTARTUP=~/.pyrc

Enjoy!

enter image description here

查看更多
登录 后发表回答