AssemblerGuy
AssemblerGuy

Reputation: 623

How can I run 2 loops simultaneously in python?

I have an application (Gtk) that has an embedded server (using circuits). Both components (The GUI and Server) have infinite loops. How can I run both loops simultaneously ?

I also need the server loop to end when the gtk loop ends.

The code for the example server

from circuits.web import Server, Controller
import os

class MyServer(Controller):

    def index(self):

        return "Hello World"


server = Server(8000)
server += MyServer()
server.run()

and the code for example gtk application

import gtk

class App:

    def __init__(self):

        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect("destroy",gtk.main_quit)
        self.window.show_all()

        gtk.main()

if __name__ == '__main__':
    app = App()

Upvotes: 2

Views: 1695

Answers (2)

Liquid_Fire
Liquid_Fire

Reputation: 7048

You could run the web server from another thread:

from threading import Thread

# ...

server = Server(8000)
server += MyServer()

web_server_thread = Thread(target=server.run)
web_server_thread.start()

gtk.main()

Upvotes: 1

David Wolever
David Wolever

Reputation: 154664

You could use the multiprocessing module to do this:

from multiprocessing import Process

def run_app():
    ... run the app ...

def run_server():
    ... run the server ...

def main():
    app = Process(target=run_app)
    app.start()

    server = Process(target=run_server)
    server.start()

    app.join()
    server.terminate()

if __name__ == "__main__":
    main()

Otherwise, if you're using Python < 2.6 on Unix, you could fiddle around with os.fork() to do the same sort of thing. Threading might work, but I don't know how well GTK or circuits plays with threads.

Upvotes: 2

Related Questions