如何在我的代码中包装python守护程序

如何在我的代码中包装python守护程序

本文介绍了如何在我的代码中包装python守护程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这里的答案,我现在有一个正在使用Tornado的工作服务器:

I have a working server using Tornado now, according to the answer here: Python BaseHTTPServer and Tornado

我想守护它。我一直在一遍又一遍地阅读,但是我不知道它如何包装我的服务器代码。我是否将所有来自 __ main __ 的代码放在我覆盖的 run()中?

I'd like to daemonize it. I have been reading over and over this daemon class example here, but I can't figure out how it wraps around my server code. Do I just put all the code from __main__ in the run() that I override?

如果它在另一个文件中,该如何对其进行子类化?确保它在同一个目录中,并使用不带.py扩展名的文件名来导入?

How do I subclass it also if it's in another file? Make sure it's in the same directory and using it's filename without .py extension to import?

我只是在寻找一种最简单的方式来运行python Web服务器脚本只不过是一个简单的调用,例如 ./ startserver.sh (例如,如果我要使用bash脚本),并且可以在没有nohup的情况下在后台运行。 out文件,所有stdout和stderr都重定向到日志文件。

I'm just looking for the simplest way to run my python web server script with nothing more than a simple call such as ./startserver.sh (for example, if I was to use a bash script) and have it run in the background with no nohup.out file and all stdout and stderr redirected to log files.

推荐答案

让我们保持简单。项目树:

Let's keep it simple. Project tree:

$ tree
.
├── daemon.py
├── main.py
├── server.py
└──  __init__.py

daemon.py 是, server.py 是, __ init __。py 是一个空文件,可让我们从目录中的其他文件导入代码。 main.py 是:

daemon.py is a Daemon class from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/, server.py is threaded version of code from Python BaseHTTPServer and Tornado, __init__.py is an empty file which allows us to import code from other files in directory. main.py is:

#!/usr/bin/env python

import sys, time, threading
from daemon import Daemon
from server import run_tornado, run_base_http_server

class ServerDaemon(Daemon):
    def run(self):
        threads = [
            threading.Thread(target=run_tornado),
            threading.Thread(target=run_base_http_server)
        ]

        for thread in threads:
            thread.start()
        for thread in threads:
            thread.join()

if __name__ == "__main__":
    daemon = ServerDaemon('/tmp/server-daemon.pid')

    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart" % sys.argv[0]
        sys.exit(2)

使用以下命令运行它:

$ python main.py start

对于第一个版本来自更改
如果__name__ =='__main __':
def myfun():并从 run() Daemon 子类的c $ c>方法。

For first version from Python BaseHTTPServer and Tornado change if __name__ == '__main__': to def myfun(): and call it from run() method of Daemon subclass.

这篇关于如何在我的代码中包装python守护程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 16:39