Snake Hernandez
Snake Hernandez

Reputation: 181

running python script in background

my script is a server that listens to clients requests and send responses. It handles requests by threading:

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 runs perfectly but it stops when i press enter. I have tried many alternatives: deamon, nohup, ... i couldn't make it run as a service in the background. i think this is a programming issue

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

Upvotes: 3

Views: 547

Answers (2)

rassa45
rassa45

Reputation: 3550

Make a PHP or HTML script devoted solely to running that python program. Then, run that PHP/HTML script on the server and you're good :).

Upvotes: 0

mazerraxuz
mazerraxuz

Reputation: 363

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

screen -S mySessionName

This starts a new screen session with the name mySessionName and attaches to that session. Inside this session you can now run your code.

Use Ctrl+A, D to detach from that session. Your code will continue to run.

To reattach to that session use:

screen -r mySessionName

To show all sessions use:

screen -ls

In a production environment however you should be looking at supervisor. This serverfault question might help.

Upvotes: 1

Related Questions