Python Twisted 后台进程
我写了一个简单的扭曲服务器 -
from twisted.internet import reactor
from twisted.internet import protocol
from twisted.web import server, resource
from twisted.internet import reactor
class Index(resource.Resource):
isLeaf = True
def render_GET(self, request):
args = request.args
print 'Args: %s' %(repr(args))
print 'Serving on PORT: 8090'
site = server.Site(Index())
reactor.listenTCP(8090, site)
reactor.run()
这个服务器在 127.0.0.1:8090
上运行得很好。需要注意的是,它是在终端(前台)运行的。当我使用 nohup
和 ctrl+Z
把这个进程放到后台时,服务器就不再响应请求了。我该怎么做才能让这个扭曲服务器在后台正常运行呢?
2 个回答
9
我建议你看看twistd。这样你就不用担心启动、进程ID文件管理等问题了。他们网站上的文档写得很好,你可以查看一下:http://twistedmatrix.com/documents/current/core/howto/basics.html。另外,别忘了查看http://twistedmatrix.com/documents/current/core/howto/tap.html,那里有关于如何实现应用程序文件的内容。
3
正如nmichael和Rakis提到的,按下“ctrl+z”后,输入“bg”可以把暂停的进程恢复为后台任务。
如果你想直接把它作为后台任务运行,可以输入
python myserver.py &
如果你想让它在你注销后也不会停止,可以输入
nohup python myserver.py &
另外要注意,nohup
并不是真正的后台运行。你可以在这里查看它们的区别:nohup和后台进程的区别是什么?
如果你真的想让你的Twisted服务器在后台运行,最好的选择是使用twistd
,就像Mark Loeser所说的那样。