Linux系统中使用virtualenv构建python虚拟环境与程序后台执行

写在前面

系统版本:Ubuntu 18.04.1 LTS
Python版本:3.6.7


构建Python虚拟环境的意义

当系统中存在多个Python项目时,若使用全局的Python环境可能会出现工具包版本冲突的问题,特别实在我们学习和使用他人的项目的时候,常常出现包版本不一致导致的各类问题。为了解决这个问题虚拟环境就是必不可少的,让每一个项目运行在独立的虚拟环境中,有效的避免不同项目环境间的干扰。

安装virtualenv
pip3 install virtualenv
创建项目目录与构建独立运行环境
#创建项目文件夹
ubuntu@VM-16-5-ubuntu:~$ mkdir mypoj
#进入文件夹
ubuntu@VM-16-5-ubuntu:~$ cd mypoj
#创建只包含基础类库的虚拟环境,命名为venv
ubuntu@VM-16-5-ubuntu:~/mypoj$ virtualenv --no-site-packages venv
Using base prefix '/usr'
New python executable in /home/ubuntu/mypoj/venv/bin/python3
Also creating executable in /home/ubuntu/mypoj/venv/bin/python
Please make sure you remove any previous custom paths from your /home/ubuntu/.pydistutils.cfg file.
Installing setuptools, pip, wheel...
done.

参数:–no-site-packages,让创建的虚拟环境中不包含任何第三方工具类

启动虚拟环境
ubuntu@VM-16-5-ubuntu:~/mypoj$ source venv/bin/activate
(venv) ubuntu@VM-16-5-ubuntu:~/mypoj$ 

通过启动./venv/bin/activate文件,便可以启动虚拟环境,正常启动后,能够发现在shell的用户等信息前多了一个虚拟环境项目名(venv)

查看虚拟环境中的包和安装第三方包

在启动虚拟环境后,即可查看环境中的包,查看方式与在系统环境中相同,添加包的方式亦是如此。

#安装wget
(venv) ubuntu@VM-16-5-ubuntu:~/mypoj$ pip install wget
Looking in indexes: http://mirrors.tencentyun.com/pypi/simple
Collecting wget
  Downloading http://mirrors.tencentyun.com/pypi/packages/47/6a/62e288da7bcda82b935ff0c6cfe542970f04e29c756b0e147251b2fb251f/wget-3.2.zip (10 kB)
Building wheels for collected packages: wget
  Building wheel for wget (setup.py) ... done
  Created wheel for wget: filename=wget-3.2-py3-none-any.whl size=9680 sha256=96a097ce50dd6b636e898010a2aecec5523fed475e23d113e1cea2a936415c2c
  Stored in directory: /home/ubuntu/.cache/pip/wheels/c5/7d/57/a14ab81e83a58c3ccf630b021656bf453e6182666d5235f035
Successfully built wget
Installing collected packages: wget
Successfully installed wget-3.2

#查看已安装的包
(venv) ubuntu@VM-16-5-ubuntu:~/mypoj$ pip list
Package    Version
---------- -------
pip        20.0.2 
setuptools 45.1.0 
wget       3.2    
wheel      0.33.6 

程序后台执行

在服务器环境下,我们常常需要将程序挂去后台执行,从而进行其他工作。在此可以使用到nohup指令。nohup 命令运行由 Command参数和任何相关的 Arg参数指定的命令组成,忽略所有挂断(SIGHUP)信号。由于爬虫项目经常需要用此种方式运行在云服务上。

nohup指令格式
nohup [command] [arg] [&]

nohup能够让指令不间断的执行,及时在我们推出shell后,指令依然执行。在其末尾添加[&]符号,则表示让指令在后台不间断的执行,程序挂去后台执行后,常常导致运行情况无法查看,因此需要将运行信息通过管道输出到其他位置。

nohup command > myout.file 2>&1 &

上述例子中:
0 – stdin (standard input),1 – stdout (standard output),2 – stderr (standard error) ;
2>&1是将标准错误(2)重定向到标准输出(&1),标准输出(&1)再被重定向输入到myout.file文件中。
挂起到后台的命令,能够使用 jobs 查看,使用 fg %n 进行关闭。
若是推出了当前的shell,再连接后,可通过 ps -aux 查看到之前的指令,并通过kill结束。

发布了29 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42404727/article/details/104087008