在后台运行python脚本

时间:2015-05-25 21:16:01

标签: python multithreading service background

我的脚本是一个侦听客户请求并发送响应的服务器。它通过线程处理请求:

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

这个脚本运行完美但是当我按回车键时它会停止。我尝试了很多替代方案:deamon,nohup,...我无法让它在后台作为服务运行。我认为这是一个编程问题

如何让这个脚本作为服务在后台运行?

2 个答案:

答案 0 :(得分:1)

要在测试/开发环境中快速简便地使用screen

screen -S mySessionName

这将启动名为mySessionName的新屏幕会话并附加到该会话。在此会话中,您现在可以运行代码。

使用 Ctrl + A D 从该会话中分离。您的代码将继续运行。

要重新连接到该会话,请使用:

screen -r mySessionName

要显示所有会话使用:

screen -ls

在生产环境中,您应该关注supervisor。这serverfault question可能会有所帮助。

答案 1 :(得分:0)

创建一个专门用于运行该python程序的PHP或HTML脚本。然后,在服务器上运行该PHP / HTML脚本,你很好:)。