如何一鍵理清大型Python項目依賴樹
?前言:
你可能時常會遇到由于包的版本不匹配導致代碼報錯的問題,由于 pip freeze 將所有依賴項顯示為二維列表,這時候如果想找到這個錯誤版本的包是比較麻煩的事情。這時候,有個工具你必須得知道,它就是 pipdeptree.
pipdeptree 是一個命令行實用程序,它能用于以依賴關系樹可視化的形式顯示已安裝的python包。
它適用于全局安裝在計算機上的各個模塊,也適用于Virtualenv等虛擬環(huán)境中的模塊。
1.安裝
你只需要在你的環(huán)境中輸入以下命令就能安裝 pipdeptree:
pip?install?pipdeptree
已通過測試的Python版本:2.7,3.5,3.6,3.7,3.8,3.9.
2.用法和示例
pip freeze 和 pipdeptree 最大的區(qū)別如下:
# pip freeze 的顯示 $ pip freeze Flask==0.10.1 itsdangerous==0.24 Jinja2==2.11.2 -e git+git@github.com:naiquevin/lookupy.git@cdbe30c160e1c29802df75e145ea4ad903c05386#egg=Lookupy MarkupSafe==0.22 pipdeptree @?file:///private/tmp/pipdeptree-2.0.0b1-py3-none-any.whl Werkzeug==0.11.2
可見,pip freeze 最多只能顯示一個依賴的列表,而在 pipdeptree ,每個模塊的依賴關系能夠非常直觀地展示出來:
$ pipdeptree Warning!!! Possibly conflicting dependencies found: * Jinja2==2.11.2 ?- MarkupSafe [required: >=0.23, installed:?0.22] ------------------------------------------------------------------------ Flask==0.10.1 ??- itsdangerous [required: >=0.21, installed:?0.24] ??- Jinja2 [required: >=2.4, installed:?2.11.2] ????- MarkupSafe [required: >=0.23, installed:?0.22] ??- Werkzeug [required: >=0.7, installed:?0.11.2] Lookupy==0.1 pipdeptree==2.0.0b1 ??- pip [required: >=6.0.0, installed:?20.1.1] setuptools==47.1.1 wheel==0.34.2
請注意這個 Warning,提示了你哪些模塊會造成其依賴的模塊版本發(fā)生沖突,這是非常有用的提示,很多時候問題就出現在這里。
不僅如此,如果存在循環(huán)性依賴,比如:
CircularDependencyA => CircularDependencyB => CircularDependencyA
它會進行如下提示:
$ pipdeptree --exclude pip,pipdeptree,setuptools,wheel Warning!!! Cyclic dependencies found: - CircularDependencyA => CircularDependencyB => CircularDependencyA - CircularDependencyB => CircularDependencyA => CircularDependencyB ------------------------------------------------------------------------ wsgiref==0.1.2 argparse==1.2.1
如果你想生成 requirements.txt,可以這么做:
$ pipdeptree -f | tee locked-requirements.txt Flask==0.10.1 ??itsdangerous==0.24 ??Jinja2==2.11.2 ????MarkupSafe==0.23 ??Werkzeug==0.11.2 gnureadline==8.0.0 -e git+git@github.com:naiquevin/lookupy.git@cdbe30c160e1c29802df75e145ea4ad903c05386#egg=Lookupy pipdeptree @ file:///private/tmp/pipdeptree-2.0.0b1-py3-none-any.whl ??pip==20.1.1 setuptools==47.1.1 wheel==0.34.2
在確認沒有沖突的依賴項后,甚至可以將其“鎖定”,其中所有包都將固定到其當前安裝的版本:
$?pipdeptree -f | sed?'s/ //g'?| sort -u > locked-requirements.txt
3. 可視化依賴樹
為了能夠可視化展示依賴樹,我們需要安裝GraphViz。安裝完成后輸入以下命令:
pipdeptree --graph-output png > dependencies.png # pipdeptree --graph-output dot > dependencies.dot # pipdeptree --graph-output pdf > dependencies.pdf # pipdeptree --graph-output svg > dependencies.svg
支持四種格式的輸出,這里png的輸出效果如下:
效果是非常不錯的,大家如果有需要清理依賴的大型項目,可以用 pipdeptree 試一下。
到此這篇關于如何一鍵理清大型Python項目依賴樹的文章就介紹到這了,更多相關 Python依賴樹清理內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!