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

17 投票
6 回答
22313 浏览
提问于 2025-04-15 14:19

在网页服务器上能否把一个Python脚本当作后台服务运行?我想这样做是为了进行套接字通信

6 个回答

2

在Windows 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>

你可以通过启动Python解释器,并把你的脚本作为参数传进去,来运行你的Python脚本:

python.exe myscript.py
7

你可以看看 Twisted 这个网站。

10

你可以把它做成一个守护进程。虽然有一个更完整的解决方案的PEP(Python增强提案),但我发现这个方法效果很好。

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

撰写回答