2016-11-04 39 views
3

我似乎記得有一個軟件包可以打印Jupyter筆記本中使用的Python軟件包的版本和相關信息,因此其結果是可重現的。但我不記得包裹的名字。你們中的任何一個人都能指引我走向正確的方向嗎Jupyter筆記本中使用的軟件包列表版本的包裝

在此先感謝!

+1

'PIP freeze'顯示有關每個包信息。或者你可以使用'conda list'。 – estebanpdl

+1

pip是否凍結打印關於筆記本內包裝的信息? – msx

+0

這些示例顯示* terminal *或*命令提示符*中的信息。 – estebanpdl

回答

5

這得到所有已安裝的軟件包

import pip #needed to use the pip functions 
for i in pip.get_installed_distributions(local_only=True): 
    print(i) 

從目前的筆記本

import types 
def imports(): 
    for name, val in globals().items(): 
     if isinstance(val, types.ModuleType): 
      yield val.__name__ 
list(imports()) 
+1

感謝您的回覆,但我正在查找僅列出相關筆記本電腦中使用的軟件包的軟件包。 – msx

+0

這個問題可能的重複 –

+0

http://stackoverflow.com/questions/4858100/how-to-list-imported-modules –

0

得到的軟件包列表,我通過合併已經提供了兩種解決方案鵝卵石這個答案。我最終想要生成一個requirements.txt類型的文件,以便與真棒Binder網站一起使用。顯然,我不想爲我的整個系統pip freeze,但我也不想爲每個筆記本創建單獨的虛擬環境(這最終是我的問題源於此)。

這將輸出一個格式良好的requirements.txt類型字符串,並處理在使用import from而不僅僅是import時涉及的一些錯綜複雜的情況。

# Get locally imported modules from current notebook 
import pip 
import types 
def get_imports(): 
    for name, val in globals().items(): 
     if isinstance(val, types.ModuleType): 
      # Split ensures you get root package, 
      # not just imported function 
      name = val.__name__.split(".")[0] 

      # Some packages are weird and have different 
      # imported names vs. system names 
      if name == "PIL": 
       name = "Pillow" 
      yield name 
imports = list(set(get_imports())) 

# The only way I found to get the version of the root package 
# from only the name of the package is to cross-check the names 
# of installed packages vs. imported packages 
requirements = [] 
for m in pip.get_installed_distributions(): 
    if m.project_name in imports and m.project_name!="pip": 
     requirements.append((m.project_name, m.version)) 

for r in requirements: 
    print("{}=={}".format(*r)) 

示例輸出:

scipy==0.19.0 
requests==2.18.1 
Pillow==5.0.0 
numpy==1.13.0 
matplotlib==2.0.2