模块除了自己编写下载,也可以使用包管理成语进行安装,包管理程序如pip

pip

pip是一个以Python计算机程序语言写成的软件包管理系统,他可以安装和管理软件包

命令

  • 列出已安装的包
    pip freeze
    pip list
    
  • 安装包
    推荐,仅安装给当前用户
    pip install --user 包名
    

    在线安装,使用==来制定版本
    pip install <包名> 
    pip install Django==1.5.3
    

    安装本地包
    pip install <目录>/<文件名>
    
  • 卸载包
    pip uninstall <包名>
    
  • 升级包
    pip install -U <包名>
    
  • 升级pip
    pip install -U pip
    
  • 显示包所在的目录
    pip show -f <包名>
    

python/python3 -m pip 指定python版本

pip默认是python2安装,不同版本的python安装的模块不通用
虽然pip3在某些程度上可以替换python3 -m pip,有的情况会报错,不推荐
指定python版本示例

python3 -m pip install 包名

示例

1. 打包我们之前写的module1包,并导入使用

打包,安装

cndaqiang@q1:~/Documents/work/0402SF10learn/python$ pip wheel module1
Collecting module1
  Downloading module1-1.3.0.zip
Building wheels for collected packages: module1
  Running setup.py bdist_wheel for module1 ... done
  Stored in directory: /home/cndaqiang/Documents/work/0402SF10learn/python
Successfully built module1
cndaqiang@q1:~/Documents/work/0402SF10learn/python$ ls
module1  module1-1.3.0-py3-none-any.whl  project
cndaqiang@q1:~/Documents/work/0402SF10learn/python$ sudo pip install module1-1.3.0-py3-none-any.whl 
The directory '/home/cndaqiang/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/cndaqiang/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Processing ./module1-1.3.0-py3-none-any.whl
Installing collected packages: module1
Successfully installed module1-1.3.0

导入使用

cndaqiang@q1:~/Documents/work/0402SF10learn/python$ python
Python 2.7.12 (default, Dec  4 2017, 14:50:18) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import module1.phy
>>> print(module1.phy.h)
6.62607004

2. pip安装慢的解决方法

[推荐]指定国内的pip源

源推荐

使用方法,以清华为例

  • 临时使用
    pip install -i https://pypi.tuna.tsinghua.edu.cn/simple 包名
    
    注意,simple 不能少, 是 https 而不是 http
  • [推荐]设为默认
    修改
    ~/.config/pip/pip.conf (Linux)
    %APPDATA%\pip\pip.ini (Windows 10)
    $HOME/Library/Application Support/pip/pip.conf (macOS)
    上述三个系统可能不存在响应配置文件,直接新建填入
    [global]
    index-url = https://pypi.tuna.tsinghua.edu.cn/simple
    
    ubutnu环境下以上修改对python2和python3同时生效

下载包文件,离线安装

从清华等pip源,一些仓库等下载包的源码,按照README安装

3. 安装包的依赖

安装一个模块,这个模块又依赖别的模块,安装依赖的包

# 生成requirements.txt文件
pip freeze > requirements.txt
# 安装requirements.txt依赖
pip install -r requirements.txt

总结--推荐的操作

添加清华的pip源,使用

python -m pip install --user 包名
python3 -m pip install --user 包名

其他的包管理程序

有很多,习惯用哪个因人而异,就不介绍了

results matching ""

    No results matching ""