我可以将 Python 脚本作为服务运行吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1423345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:13:47  来源:igfitidea点击:

Can I run a Python script as a service?

pythonweb-servicessocketswebserver

提问by TheFlash

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

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

采纳答案by Robert

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

你可以让它成为一个守护进程。有一个更完整的解决方案的 PEP,但我发现这很有效。

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))

回答by Fragsworth

You might want to check out Twisted.

您可能想查看Twisted

回答by jldupont

There is the very helpful Pypi packagewhich is the basis for my daemons written in Python.

有一个非常有用的Pypi 包,它是我用 Python 编写的守护进程的基础。

回答by Peter Parker

on XP and later you can use the sc.exeprogram to use any .exe as service:

在 XP 及更高版本上,您可以使用sc.exe程序将任何 .exe 用作服务:

>sc create
Creates a service entry in the registry and Service Database.
SYNTAX:
sc create [service name] [binPath= ] <option1> <option2>...
CREATE OPTIONS:
NOTE: The option name includes the equal sign.
 type= <own|share|interact|kernel|filesys|rec>
       (default = own)
 start= <boot|system|auto|demand|disabled>
       (default = demand)
 error= <normal|severe|critical|ignore>
       (default = normal)
 binPath= <BinaryPathName>
 group= <LoadOrderGroup>
 tag= <yes|no>
 depend= <Dependencies(separated by / (forward slash))>
 obj= <AccountName|ObjectName>
       (default = LocalSystem)
 DisplayName= <display name>
 password= <password>

You can start your pythonscript by starting the python interpreter with your script as argument:

您可以通过使用您的脚本作为参数启动 python 解释器来启动您的 pythonscript:

python.exe myscript.py

回答by mjv

Assuming this is for Windows, see this recipe based on srvany

假设这是针对 Windows 的,请参阅基于 srvany 的这个配方

回答by Unknown

If you are talking about linux, it is as easy as doing something like ./myscript.py &

如果您在谈论 linux,那么就像执行 ./myscript.py & 之类的事情一样简单