局域网内部搭建pip源

python的pip源的搭建

原因

局域网无法连接互联网,每次安装python模块需要在公网机器下载、刻盘、导入、安装、再去下载依赖......一来一回不仅消耗很多光盘,并且浪费大量的开发时间。

下载pypi所有模块

首先安装msys2,并且添加到环境变量,在命令行中能够使用wget命令,如果不添加环境变量则需要使用wget.exe的绝对路径。
此处使用的是阿里的镜像源,镜像源2020年初大约9T,之后会慢慢增加,需要提前准备好存储。下载时间可能比较长,需要耐心等待。
下载下来主要是两个文件夹:simple和packages

#https://mirrors.aliyun.com/pypi/simple/
import multiprocessing,queue,os
from bs4 import BeautifulSoup

#下载进程
def download_process(url):
	#wget -m -t 10 -c -np -q -b --execute robots=off https://mirrors.aliyun.com/pypi/packages/00/00/
	out=os.popen("C:\\msys64\\usr\\bin\\wget -m -t 10 -T 180 -c -q --execute robots=off {url}".format(url=url)).read()
	if out!="":
		print("ERROR:{url}".format(url=url))
		with open("error_simple.log","a") as log:
			log.write("ERROR:{url}\n".format(url=url))
	else:
		print("下载完成:{url}".format(url=url))
		with open("success_simple.log","a") as log:
			log.write("下载完成:{url}\n".format(url=url))
	
if __name__=="__main__":
	#多线程支持and参数获取
	multiprocessing.freeze_support()
	# 下载所有模块列表
	os.popen("C:\\msys64\\usr\\bin\\wget https://mirrors.aliyun.com/pypi/simple/").read()
	# 获取所有的a标签中的连接
	html=BeautifulSoup(open("index.html",'r',encoding="utf-8"),"html.parser")
	tag=html.select('a[href]')
	urls=[]
	for ahref in tag:
		urls.append("https://mirrors.aliyun.com/pypi/simple/"+ahref.get("href"))

	#创建任务队列
	TaskQue=queue.Queue()
	for i in urls:
		TaskQue.put(i)

	# 开启下载线程
	pool=multiprocessing.Pool(processes=16) # 开启16个进程,当然也可以根据CPU数目开启进程,processes=multiprocessing.cpu_count()
	for i in range(TaskQue.qsize()):
		TaskQue_One=TaskQue.get()
		pool.apply_async(download_process,(TaskQue_One,))
	pool.close()
	pool.join()

部署nginx

nginx服务器局域网地址为<192.168.1.195>
如果内网有web服务可以直接挂载到相应目录下,开启目录遍历功能即可。我是使用源码搭建的nginx服务(具体步骤见https://www.jianshu.com/p/172063887a51

# 修改配置文件
vim /usr/local/nginx/conf/nginx.conf
# 在你自己自定义的目录下添加如下3行内容,我是直接放在根目录下,所以追加在location /{...}这个下面
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
# 重启nginx服务
systemctl restart nginx

使用pypi源

配置文件位置:
Windows:win+R---输入%USERPROFILE%(或者%HOMEPATH%)之后回车---在此目录中新建文件夹pip---在pip文件夹中新建文件pip.ini
Linux:vim ~/.pip/pip.conf
配置文件内容如下:

[global]
index-url = http://192.168.1.195/pypi/simple
[install]
trusted-host = 192.168.1.195