Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I run a Python script as a service?

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

like image 575
Robin Rodricks Avatar asked Sep 14 '09 19:09

Robin Rodricks


People also ask

How do I host a Python script from the server?

Open the file and add the necessary code. NOTE: The file should start with the path to the Python scripts that is /usr/bin/python on our servers, but you can run the whereis python command via SSH to check the directory. To save the changes, click Crtl+O and press Enter for Windows or Command+O for Mac OS.


2 Answers

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))
like image 104
Robert Avatar answered Sep 30 '22 04:09

Robert


You might want to check out Twisted.

like image 45
Fragsworth Avatar answered Sep 30 '22 02:09

Fragsworth