1

I have this code where it loads necessary files and prints necessary information when the server starts but inside if __name__ == "__main__": I'm starting a background process as well then finally app.run() is executed.

My problem is after loading all and comes to the starting of background process it starts to print and load everything from beginning again. And also it does the same when the server get its first request (GET/POST). How can I make it load only once?

import web
from multiprocessing import Process
import scripts
print 'Engine Started'
# Code to load and print necessary stuff goes here...

urls = (
    '/test(.*)', 'Test'
)

class Test():

    def GET(self,r):
        tt = web.input().t
        print tt
        return tt


if __name__ == "__main__":
    try:
        print 'Cache initializing...'
        p = Process(target=scripts.initiate_cleaner)
        p.start() # Starts the background process
    except Exception, err:
        print "Error initializing cache"
        print err

    app = web.application(urls, globals())
    app.run()

So this loads thrice ('Engine Started' prints thrice) after starting process and requesting from localhost:8080/test?t=er

I went through this but it solves the problem in flask and I use web.py

Community
  • 1
  • 1
Marlon Abeykoon
  • 11,927
  • 4
  • 54
  • 75
  • 1
    `print 'Engine Started'` is not inside `if __name__ == "__main__":` – Padraic Cunningham May 10 '16 at 09:12
  • @PadraicCunningham so you are saying that I should put all the loading codes and prints inside `if __name__ == "__main__":` ? – Marlon Abeykoon May 10 '16 at 09:15
  • Only what is inside the `if __name__ == "__main__"` won't be executed when anything is imported from the file. That is the main point of using it, only when you actually execute the file will anything inside the if be run. – Padraic Cunningham May 10 '16 at 09:16

1 Answers1

1

I'm not sure why this surprises you, or why it would be a problem. A background process is by definition a separate process from the web process; each of those will import the code, and therefore print that message. If you don't want to see that message, put it inside the if __name__ block.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • ok thanks My problem solved once I moved the code to the said place. But why does it go through the whole code when run a process or when 1st request comes. not for 2nd and later requests? – Marlon Abeykoon May 10 '16 at 10:08
  • Because after the first request the process is already running and the code is already imported. – Daniel Roseman May 10 '16 at 10:08