Running python script in background

my script is a server that listens for client requests and sends responses. It handles requests by streaming:

class Server:

def __init__(self):
    self.host = ''
    self.port = 50000
    self.backlog = 5
    self.size = 1024
    self.server = None
    self.threads = []

def open_socket(self):
    try:
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind((self.host,self.port))
        self.server.listen(5)
    except socket.error, (value,message):
        if self.server:
            self.server.close()
        print "Could not open socket: " + message
        sys.exit(1)

def run(self):
    self.open_socket()
    input = [self.server,sys.stdin]
    running = 1
    while running:
        inputready,outputready,exceptready = select.select(input,[],[])

        for s in inputready:

            if s == self.server:
                # handle the server socket
                c = Client(self.server.accept())
                c.start()
                self.threads.append(c)

            elif s == sys.stdin:
                # handle standard input
                junk = sys.stdin.readline()
                running = 0 

    # close all threads

    self.server.close()
    for c in self.threads:
        c.join()

class Client(threading.Thread):
def __init__(self,(client,address)):
    threading.Thread.__init__(self)
    self.client = client
    self.address = address
    self.size = 1024

def run(self):
    running = 1
    while running:
        data = self.client.recv(self.size)
        if data:
    data2 = data.split()
    if data2[0] == 'Hello':
            status = 'Hello'
                #fetch from database users by location 
                reply= '6'


        if data2[0] == 'Index':
                status = 'Index'
        #fetch from database users by location 
            reply='I'

        db = MySQLdb.connect(host="localhost", # your host, usually localhost
                        user="root", # your username
                        passwd="Rambo_9134", # your password
                        db="secure_login") # name of the data base

        # you must create a Cursor object. It will let
        #  you execute all the queries you need
        cur = db.cursor() 

        # Use all the SQL you like
        cur.execute("SELECT ml.member,m.username FROM locations l JOIN memberlocation ml ON(l.id = ml.location) JOIN members m ON(m.id = ml.member) where l.id = 1;")
        # print all the first cell of all the rows
        data = []
        for row in cur.fetchall() :
                print row[1]
            data.append({row[0]:row[1]})
            print 'JSON', json.dumps(data)
        reply = data        


        self.client.send(json.dumps(reply))
        else:
            self.client.close()
            running = 0

if __name__ == "__main__":
s = Server()
s.run()

      

this script works fine, but it stops when i press enter button. I tried many alternatives: deamon, nohup, ... I couldn't get it to run as a service in the background. i think this is a programming problem

how can I make this script run in the background as a service?

+3


source to share


2 answers


For a quick and easy way, in test / dev environment, you can use screen

.

screen -S mySessionName

      

This starts a new session named session mySessionName

and joins that session. Within this session, you can run your code.

Use Ctrl+ A, Dto disconnect from this session. Your code will continue to work.

To reconnect to this session use:



screen -r mySessionName

      

To show all sessions use:

screen -ls

      

In a work environment, however, you have to look supervisor

. This server-side question might help.

+1


source


Make a PHP or HTML script dedicated exclusively to running this python program. Then run this PHP / HTML script on the server and you're good :).



0


source







All Articles