如何导出,导入项目依赖包列表

我们在使用pycharm的时候,pycharm中的虚拟环境依赖包需要导出成一个文件,方便给他人运行项目,这个时候,如果使用终端导出的是系统环境,不是虚拟环境,所以不能使用生成requirement.txt

一般命令为:

pip freeze > requirements.txt

但是在windows终端下是不可以使用的:所以你需要使用以下代码,进行导出,将如下代码新建一个Python文件,放在项目根路径下,然后运行就可以了

windows和linux下均可以正常生成。windows下带有空格的目录,可以正常生成。

 1 import os
 2 
 3 import platform
 4 
 5 import sys
 6 
 7 import subprocess
 8 
 9 # 找到当前目录
10 
11 project_root = os.path.dirname(os.path.realpath(__file__))
12 
13 # project_root = os.path.realpath(__file__)
14 
15 print('当前目录' + project_root)
16 
17 # 不同的系统,使用不同的命令语句
18 
19 if platform.system() == 'Linux':
20 
21 command = sys.executable + ' -m pip freeze > ' + project_root + '/requirements.txt'
22 
23 if platform.system() == 'Windows':
24 
25 command = '"' + sys.executable + '"' + ' -m pip freeze > "' + project_root + '\\requirements.txt"'
26 
27 # # 拼接生成requirements命令
28 
29 print(command)
30 
31 #
32 
33 # 执行命令。
34 
35 # os.system(command) #路径有空格不管用
36 
37 os.popen(command) #路径有空格,可用
38 
39 # subprocess.call(command, shell=True) #路径有空格,可用

 

导入:

pip install -r requirements.txt

 

————————————————
版权声明:本文为CSDN博主「暗淡了乌云」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_35255032/article/details/113028480

posted @ 2022-02-26 15:39  搬砖在路上  阅读(346)  评论(0编辑  收藏  举报