我可以将 Python 脚本作为服务运行吗? [英] Can I run a Python script as a service?

查看:60
本文介绍了我可以将 Python 脚本作为服务运行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在网络服务器上将 Python 脚本作为后台服务运行?我想为 套接字通信执行此操作.

Is it possible to run a Python script as a background service on a webserver? I want to do this for socket communication.

推荐答案

您可以将其设为守护程序.有一个更完整的解决方案的 PEP,但我发现这很有效.

You can make it a daemon. There is a PEP for a more complete solution, but I have found that this works well.

import os, sys

def become_daemon(our_home_dir='.', out_log='/dev/null', err_log='/dev/null', pidfile='/var/tmp/daemon.pid'):
    """ Make the current process a daemon.  """

    try:
        # First fork
        try:
            if os.fork() > 0:
                sys.exit(0)
        except OSError, e:
            sys.stderr.write('fork #1 failed" (%d) %s\n' % (e.errno, e.strerror))
            sys.exit(1)

        os.setsid()
        os.chdir(our_home_dir)
        os.umask(0)

        # Second fork
        try:
            pid = os.fork()
            if pid > 0:
                # You must write the pid file here.  After the exit()
                # the pid variable is gone.
                fpid = open(pidfile, 'wb')
                fpid.write(str(pid))
                fpid.close()
                sys.exit(0)
        except OSError, e:
            sys.stderr.write('fork #2 failed" (%d) %s\n' % (e.errno, e.strerror))
            sys.exit(1)

        si = open('/dev/null', 'r')
        so = open(out_log, 'a+', 0)
        se = open(err_log, 'a+', 0)
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())
    except Exception, e:
        sys.stderr.write(str(e))

这篇关于我可以将 Python 脚本作为服务运行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆