57

我想在 CENTOS 服务器上运行一个 python 脚本:

#!/usr/bin/env python
import socket
try:    
    import thread 
except ImportError:
    import _thread as thread #Py3K changed it.
class Polserv(object):
    def __init__(self):
        self.numthreads = 0
        self.tidcount   = 0
        self.port       = 843
        self.sock       = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(('100.100.100.100', self.port))
        self.sock.listen(5)
    def run(self):
        while True:
            thread.start_new_thread(self.handle, self.sock.accept()) 
    def handle(self,conn,addr):
        self.numthreads += 1
        self.tidcount   += 1
        tid=self.tidcount
        while True:
            data=conn.recv(2048)
            if not data:
                conn.close()
                self.numthreads-=1
                break
            #if "<policy-file-request/>\0" in data:
            conn.sendall(b"<?xml version='1.0'?><cross-domain-policy><allow-access-from domain='*' to-ports='*'/></cross-domain-policy>")
            conn.close()
            self.numthreads-=1
            break
        #conn.sendall(b"[#%d (%d running)] %s" % (tid,self.numthreads,data) )
Polserv().run()

我正在使用$ python flashpolicyd.py它,它工作正常......问题是:即使在我关闭终端(控制台)之后,如何保持这个脚本运行?

4

5 回答 5

79

我提出两个建议:

监督者

1)安装supervisor包(更详细的说明here):

sudo apt-get install supervisor

2) 在以下位置为您的守护程序创建一个配置文件/etc/supervisor/conf.d/flashpolicyd.conf

[program:flashpolicyd]
directory=/path/to/project/root
environment=ENV_VARIABLE=example,OTHER_ENV_VARIABLE=example2
command=python flashpolicyd.py
autostart=true
autorestart=true

3)重新启动supervisor加载你的新.conf

supervisorctl update
supervisorctl restart flashpolicyd

systemd(如果当前由您的 Linux 发行版使用)

[Unit]
Description=My Python daemon

[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/project/main.py
WorkingDirectory=/opt/project/
Environment=API_KEY=123456789
Environment=API_PASS=password
Restart=always
RestartSec=2

[Install]
WantedBy=sysinit.target

将此文件放入/etc/systemd/system/my_daemon.service并使用systemctl daemon-reload && systemctl enable my_daemon && systemctl start my_daemon --no-block.

查看日志:

systemctl status my_daemon

于 2013-05-07T13:36:07.753 回答
79

I use this code to daemonize my applications. It allows you start/stop/restart the script using the following commands.

python myscript.py start
python myscript.py stop
python myscript.py restart

In addition to this I also have an init.d script for controlling my service. This allows you to automatically start the service when your operating system boots-up.

Here is a simple example to get your going. Simply move your code inside a class, and call it from the run function inside MyDeamon.

import sys
import time

from daemon import Daemon


class YourCode(object):
    def run(self):
        while True:
            time.sleep(1)


class MyDaemon(Daemon):
    def run(self):
        # Or simply merge your code with MyDaemon.
        your_code = YourCode()
        your_code.run()


if __name__ == "__main__":
    daemon = MyDaemon('/tmp/daemon-example.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)

Upstart

If you are running an operating system that is using Upstart (e.g. CentOS 6) - you can also use Upstart to manage the service. If you use Upstart you can keep your script as is, and simply add something like this under /etc/init/my-service.conf

start on started sshd
stop on runlevel [!2345]

exec /usr/bin/python /opt/my_service.py
respawn

You can then use start/stop/restart to manage your service.

e.g.

start my-service
stop my-service
restart my-service

A more detailed example of working with upstart is available here.

Systemd

If you are running an operating system that uses Systemd (e.g. CentOS 7) you can take a look at the following Stackoverflow answer.

于 2013-05-07T13:19:17.843 回答
9

我的非 pythonic 方法是使用 & 后缀。那是:

python flashpolicyd.py &

停止脚本

killall flashpolicyd.py

带有 disown 的管道和后缀也会将该过程置于父级(上)下:

python flashpolicyd.pi & disown
于 2014-05-04T15:12:07.710 回答
5

首先在您的应用程序中导入 os 模块,而不是使用 getpid 函数获取 pid 的应用程序并保存在文件中。例如:

import os
pid = os.getpid()
op = open("/var/us.pid","w")
op.write("%s" % pid)
op.close()

并在 /etc/init.d 路径中创建一个 bash 文件:/etc/init.d/servername

PATHAPP="/etc/bin/userscript.py &"
PIDAPP="/var/us.pid"
case $1 in 
        start)
                echo "starting"
                $(python $PATHAPP)
        ;;
        stop)
                echo "stoping"
                PID=$(cat $PIDAPP)
                kill $PID
        ;;

esac

现在,您可以使用 down 命令启动和停止您的应用程序:

服务服务器名停止服务服务器名开始

或者

/etc/init.d/servername 停止 /etc/init.d/servername 启动

于 2014-05-04T14:57:18.660 回答
2

对于我的python脚本,我使用...

启动 python 脚本:

start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --exec $DAEMON

停止 python 脚本:

PID=$(cat $PIDFILE)
kill -9 $PID
rm -f $PIDFILE

PS:抱歉英语不好,我来自智利:D

于 2016-07-11T20:43:06.977 回答