[系統互動篇] 如何在 python notebook 上直接安裝套件 - tsungjung411/python-study GitHub Wiki

關鍵字

  • python notebook
  • jupyter notebook
  • ipython

python --version

  • 方法一:
    import sys
    !{sys.executable} --version
    
    執行結果
    Python 3.7.8
    
  • 方法二:
    # both okay
    !python --version
    ! python --version
    
    執行結果
    Python 3.7.8
    

pip install

import sys
!{sys.executable} -m pip install pandas-profiling

可直接在 python 環境安裝 (2021.03.10)

import os
os.system('pip --version')
os.system('pip install --upgrade pip')

或是

import sys
import os

python_path = sys.executable
cmd = python_path + ' -m pip install --upgrade pip'
os.system(cmd)
import importlib.util
importlib.util.find_spec('sklearn')
# ModuleSpec(name='sklearn', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7f9b76467f98>, 
# origin='/home/diatango_lin/tj_tsai/workspace/ml_scikit/ml-env/lib/python3.6/site-packages/sklearn/__init__.py', 
# submodule_search_locations=['/home/diatango_lin/tj_tsai/workspace/ml_scikit/ml-env/lib/python3.6/site-packages/sklearn'])

if importlib.util.find_spec('sklearn') == None:
   import os
   os.system('pip install sklearn')

寫好的 pip_install 函數

v1 (只能在純 python 環境上跑)

def pip_install(python_lib):
    import importlib.util
    import sys
    import os
    
    module = importlib.util.find_spec(python_lib)
    if module == None:
        python_path = sys.executable
        cmd = python_path + ' -m pip install ' + python_lib
        os.system(cmd)
    else:
        print('module info:\n  ', module)
        print('module location:\n  ', module.submodule_search_locations)
        print('The package "%s" already exists.' % python_lib)

pip_install('sklearn')

v2 (可以在 python notebook 環境上跑)

import importlib

def install_and_import(package):
    '''
    Install and import the given package.
    '''
    module_spec = importlib.util.find_spec(package)
    if module_spec == None:
        print('$ pip3 install', package)
        !pip3 install $package
    else:
        print('{} has been installed!'.format(package))
    
    module = importlib.import_module(package)
    print("- package name:", module.__name__)
    print("- package version:", module.__version__)
    print("- package path:", module.__path__)
    return module

pd = install_and_import('pandas')