Quantcast
Channel: Bashタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 2722

Python インタラクティブ モードのプロンプトに色づけ (ついでに cmd.exe, PowerShell, Bash のプロンプトにも言及)

$
0
0
動機といきさつ CLI のプロンプトは色がついていたほうが見やすいし、それだけで使うのがちょっと楽しくなる感じがします。 Windows のコマンド プロンプトならば %SystemRoot%\System32\cmd.exe /f:on /k prompt $e[36m$p$g$e[0m というショートカットをつくるとか…。 PowerShell ならば $PROFILE.CurrentUserAllHosts ファイルに function prompt { #"PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "; $principal = [Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent() $foregroundColor = if (Test-Path -Path Variable:\PSDebugContext) { [ConsoleColor]::Yellow } elseif ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { [ConsoleColor]::Red } else { [ConsoleColor]::Cyan } Write-Host -Object 'PS ' -NoNewline -ForegroundColor $foregroundColor Write-Host -Object "$($executionContext.SessionState.Path.CurrentLocation)" -ForegroundColor Magenta Write-Output -InputObject "$('>' * ($nestedPromptLevel + 1)) " # .Link # https://go.microsoft.com/fwlink/?LinkID=225750 # .ExternalHelp System.Management.Automation.dll-help.xml } とかいておくとか…1。 Cygwin のデフォルトのプロンプトが好きで、他の GNU/Linux ディストロでも同様の記述を ~/.bashrc に追記していたりします。 PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n\$ ' \e[32m, \e[33m, \e[0m が色を指定している部分です2。 本題 Python のインタラクティブ モードのプロンプト文字列は sys.ps1 と sys.ps2 に入っています。また、環境変数 PYTHONSTARTUP に指定したファイルの内容を起動時に読み込んでくれます3。 .bashrc export PYTHONSTARTUP=$HOME/.pythonrc.py .pythonrc.py import sys sys.ps1 = '\001\033[31m\002>>>\001\033[0m\002 ' sys.ps2 = '\001\033[31m\002...\001\033[0m\002 ' \033 が ESC です。ここでは The Python Tutorial のコード表示部分にならって赤 (31) にしています。 なお、ここでのハマりどころはエスケープ シーケンス部分を \001 と \002 でくくってやらないと Ctrl + r などの readline 編集で行の表示がくずれてしまうことです4。 https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_prompts ↩ https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters ↩ https://docs.python.org/3/tutorial/appendix.html#the-interactive-startup-file ↩ https://stackoverflow.com/questions/9468435/how-to-fix-column-calculation-in-python-readline-if-using-color-prompt ↩

Viewing all articles
Browse latest Browse all 2722

Trending Articles