问题描述
我正在使用Cherrypy框架在服务器上运行我的python代码.但是,当负载增加时,该过程将停止工作.
I am using Cherrypy framework to run my python code on server. But the process stops working when the load increases.
每次发生这种情况时,我都必须手动去启动python代码.我有什么办法可以将Gunicorn与Cherrypy结合使用,以便Gunicorn可以在停止工作时自动启动代码.
Every time this happens I have to manually go and start the python code. Is there any way i can use Gunicorn with Cherrypy so that Gunicorn can start the code automatically when it stops working.
在这种情况下,任何其他解决方案也将起作用.只是要确保python程序不会停止工作.
Any other solution will also work in this case. Just want to make sure that the python program does not stop working.
推荐答案
我使用cron来每隔几分钟检查一次内存负载,并在内存超过500MB时重置Cherrypy -这样,Web主机就不会向我抱怨与电子邮件.功能结束时,服务器上的某些内容不会释放内存,因此这是一个务实的解决方法.
I use a cron that checks the memory load every few minutes and resets cherrypy when the memory exceeds 500MB -- so that the web host doesn't complain to me with emails. Something on my server doesn't release memory when a function ends as it should, so this is a pragmatic work around.
此黑客可能很奇怪,因为我使用HTTP请求对其进行了重置,但这是因为我花了数小时试图弄清楚如何使用BASH来做到这一点,并放弃了.可以.
This hack may be weird because I reset it using an HTTP request, but that's because I spent hours trying to figure out how to do this withing the BASH and gave up. It works.
*/2 * * * * /usr/local/bin/python2.7 /home/{mypath}/cron_reset_cp.py > $HOME/cron.log 2>&1
还有cron_reset_cp.py中的代码...
#cron for resetting cherrypy /cp/ when 500+ MB
import os
#assuming starts in /home/my_username/
os.chdir('/home/my_username/cp/')
import mem
C = mem.MemoryMonitor('my_username') #this function adds up all the memory
memory = int(float(C.usage()))
if memory > 500:#MB
#### Tried: pid = os.getpid() #current process = cronjob --- THIS approach did not work for me.
import urllib2
cp = urllib2.urlopen('http://myserver.com/cp?reset={password}')
然后我添加了此功能,以通过cron或从任何浏览器进行github更新后重置Cherrypy(假设只有我知道{password})
Then I added this function to reset the cherrypy via cron OR after a github update from any browser (assuming only I know the {password})
重置网址为 http://myserver.com/cp?reset= {密码}
The reset url would be http://myserver.com/cp?reset={password}
def index(self, **kw):
if kw.get('reset') == '{password}':
cherrypy.engine.restart()
ip = cherrypy.request.headers["X-Forwarded-For"] #get_client_ip
return 'CherryPy RESETTING for duty, sir! requested by '+str(ip)
MemoryMonitor部分来自此处:如何获取Python中当前的CPU和RAM使用情况?
The MemoryMonitor part is from here:How to get current CPU and RAM usage in Python?
这篇关于停止工作时重新启动Python.py的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!