DEV Community

codemee
codemee

Posted on • Edited on

讓 pipenv 在 powershell 下開啟 shell 時顯示專案資料夾

不確定是我自己安裝的問題, 還是本來就如此, 在我的 powershell 中啟動 pipenv shell, 並不會在提示符號開頭顯示專案資料夾或是虛擬環境名稱, 像是這樣:

~/code/python/py3.10.11
# pipenv shell
Launching subshell in virtual environment...
PowerShell 7.4.1
Loading personal and system profiles took 532ms.
~/code/python/py3.10.11
#
Enter fullscreen mode Exit fullscreen mode

但是在 cmd 下卻沒問題:

C:\Users\meebo\code\python\py3.10.11>pipenv shell
Launching subshell in virtual environment...
Microsoft Windows [版本 10.0.22621.3007]
(c) Microsoft Corporation. 著作權所有,並保留一切權利。

(py3.10.11-tuTXJP8y) C:\Users\meebo\code\python\py3.10.11> 
Enter fullscreen mode Exit fullscreen mode

它會把專案資料夾對應的虛擬環境名稱顯示出來。

經過搜尋, 似乎大家都有一樣的問題, 經過善心人士提供解決方案, 只要在 powershell 的 profile 中加入以下腳本即可:

if ($env:PIPENV_ACTIVE -eq 1) {

    function _OLD_PROMPT { "" }
    Copy-Item -Path function:prompt -Destination function:_OLD_PROMPT


    $_PROMPT_PREFIX = (($env:VIRTUAL_ENV -split "\\")[-1] -split "-")[0]

    function prompt {
        Write-Host -NoNewline -ForegroundColor Green "($_PROMPT_PREFIX) " 
        _OLD_PROMPT

    }
}
Enter fullscreen mode Exit fullscreen mode

這個腳本會在你的提示符號開頭插入專案資料夾, 像是這樣:

~/code/python/py3.10.11
# pipenv shell
Launching subshell in virtual environment...
PowerShell 7.4.1
Loading personal and system profiles took 1354ms.
(py3.10.11) ~/code/python/py3.10.11
#
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay