Ubuntu16.04下采用Python3.7虚拟环境,开机让程序自启动的设置方法
在网上查了几天,只看到Python虚拟环境如何安装部署,一般用户登录的时候都是采用以下操作进入和退出虚拟环境:
进入虚拟环境:source ~/my_env/bin/activate
说明:这个操作其实就是将虚拟目录下bin目录路径添加到了系统搞得path下了。
退出虚拟环境:deactivate
但是网上很少有帖子告知:在Ubuntu系统下,若采用虚拟环境,怎么设置开机python程序自动启动运行。
这个问题其实非常简单,写下此帖子,奉献给大众程序猿 。一般来说,程序需要自启动,一般在/etc/rc.local文件中的exit 0前面增加自己的脚本程序。亲测可采用以下方法:
1.新建auto_run.sh:(项目程序文件在/home/wuditnt/FlaskWebApi目录中)
#!/bin/bash source /root/my_env/bin/activate cd /home/wuditnt/FlaskWebApi python tornado_server.py &
注意:
1)第一行必须是#!/bin/bash,表示采用bash来运行脚本,不然source命令无法识别。因为在Ubuntu 当中执行脚本默认的使用的是dash,而非bash。参考:https://www.cnblogs.com/davygeek/p/6218582.html
2)之后就是进入虚拟环境,然后到当前目录执行python程序。
3)如果不用source命令,python程序的路径就得用完整路径,本例的路径是:/root/my_env/bin/python,如下:
#!/bin/bash cd /home/wuditnt/FlaskWebApi /root/my_env/bin/python tornado_server.py &
2.在/etc/rc.local文件中的exit 0前面,将auto_run.sh加上。
#!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "exit 0" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing. #自动执行启动脚本 /home/wuditnt/FlaskWebApi/auto_run.sh exit 0
这样就可以在主机重启后,自动运行虚拟换环境下的python程序了。
另外,在centos系统在,估计应该也是可以的。centos下默认采用的是bash。
很不错!