下面是内幕。
- 首先,我将 EC2 实例与 Amazon Linux(原始实例,而不是 Amazon Linux 2)一起使用,将我限制为 sysV 而不是 systemd。
- 我有一个在 CherryPy WSGI 服务器上运行的 Flask 应用服务器,前面有一个 Nginx 反向代理。
- WSGI 服务器和应用服务器都在 python3 virtualenv 中。
- 服务器在 virtualenv 中运行得很好。
- 放一个#!与服务器文件顶部的 virtualenv python bin 的位置一致,我可以通过输入服务器脚本的完整路径从系统上的任何位置运行服务器(无需先激活 virtualenv):
/path/to/server.py
- 但是,当我尝试从 init.d 脚本中运行它时,出现
ModuleNotFoundError: No module named 'cherrypy'
错误。 - 我也尝试使用 activate_this.py,得到相同的结果。
这是一些(匿名)代码,看看是否有帮助:
服务器.py:
#!/path/to/myVenv/bin/python
# Activate virtualenv from within this script:
# Commented out as it doesn't seem to help
# activate_this = "/path/to/myVenv/bin/activate_this.py"
# exec(compile(open(activate_this, "rb").read(), activate_this, 'exec'), dict(__file__=activate_this))
# Import your application as:
# from wsgi import application
# Example:
from wsgi import application
# Import CherryPy
import cherrypy
if __name__ == '__main__':
# Mount the application
cherrypy.tree.graft(application, "/")
# Other CherryPy stuff here. Not relevant as script doesn't progress this far
# when it breaks and works fine when it doesn't
/etc/init.d/crowded(基于https://www.cyberciti.biz/tips/linux-write-sys-v-init-script-to-start-stop-service.html)
#!/bin/bash
#
# chkconfig: 35 90 12
# description: CrowdEd server
#
# Based on file found at
# https://www.cyberciti.biz/tips/linux-write-sys-v-init-script-to-start-stop-service.html
PATH=/path/to/myVenv/bin
# Get function from functions library
. /etc/init.d/functions
# Start the service FOO
start() {
initlog -c "echo -n Starting CrowdEd server: "
/path/to/server.py &
### Create the lock file ###
touch /var/lock/subsys/crowded
success $"CrowdEd server startup"
echo
}
# Restart the service FOO
stop() {
initlog -c "echo -n Stopping CrowdEd server: "
killproc server.py
### Now, delete the lock file ###
rm -f /var/lock/subsys/crowded
echo
}
### main logic ###
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status crowded
;;
restart|reload|condrestart)
stop
start
;;
*)
echo $"Usage: $0 {start|stop|restart|reload|status}"
exit 1
esac
exit 0
TL;DR:从控制台编写的 Python 脚本在从 init.d 脚本调用时不起作用,特别是在从 init 脚本调用时无法链接 virtualenv 中的库,尽管从控制台调用时链接它们很好。我不知道为什么。