Using Python to implement a method that only overloads the modified process in the server

Source: Internet
Author: User
Now that we've set up a web app framework completely, from the backend API to the front-end MVVM, the process has run through.

Before you continue working, notice that each time you modify the Python code, you must ctrl-c stop the server and restart the command line before the change takes effect.

In the development phase, every day to modify, save dozens of times the code, each time the save is manually so much trouble, seriously reducing our development efficiency. Is there a way to get the server to detect code changes and reload it automatically?

Django's development environment can be automatically reloaded in debug mode, and if we write a server that can do this, it can greatly improve development efficiency.

Unfortunately, Django does not have this function independent, without Django can not enjoy, how to do?

In fact, Python itself provides the ability to reload the module, but not all modules can be re-loaded. Another idea is to detect code changes in the WWW directory, and automatically restart the server once changes are made.

According to this idea, we can write an auxiliary program pymonitor.py, let it start wsgiapp.py, and always monitor the WWW directory code changes, there are changes, the current wsgiapp.py process to kill, and then restart, completed the server process automatic restart.

To monitor changes in catalog files, we do not need to manually scan our own, Python's third-party library watchdog can use the operating system's API to monitor changes in directory files and send notifications. We first install with Easy_install:

$ easy_install watchdog

Use watchdog to receive notification of file changes and, if it is a. py file, to automatically restart the wsgiapp.py process.

Use Python's subprocess to start and stop the process and redirect the input output to the input and output of the current process:

#!/usr/bin/env pythonimport OS, sys, time, subprocessfrom watchdog.observers import observerfrom watchdog.events import F Ilesystemeventhandlerdef log (s): print ' [Monitor]%s '% Sclass myfilesystemeventhander (filesystemeventhandler): Def __i    nit__ (Self, FN): Super ("Myfilesystemeventhander, Self"). __init__ () Self.restart = fn def on_any_event (self, event): If Event.src_path.endswith ('. py '): Log (' Python source file changed:%s '% Event.src_path) Self.restart () Comman d = [' echo ', ' OK ']process = Nonedef kill_process (): Global Process if process:log (' Kill process [%s] ... '% PROCESS.P ID) Process.kill () process.wait () log (' process ended with code%s. '% Process.returncode ') process = Nonedef St Art_process (): Global process, command log (' Start process%s ... '% '. Join (command)) process = subprocess. Popen (Command, Stdin=sys.stdin, Stdout=sys.stdout, Stderr=sys.stderr) def restart_process (): kill_process () Start_ Process () def start_watch (Path, callback): OBServer = Observer () observer.schedule (Myfilesystemeventhander (restart_process), Path, recursive=true) Observer.start () log (' Watching directory%s ... '% path) start_process () Try:while True:time.sleep (0.5) except Keyboardinte Rrupt:observer.stop () Observer.join () if __name__ = = ' __main__ ': argv = sys.argv[1:] If not argv:print (' Usage:. /pymonitor your-script.py ') exit (0) If argv[0]!= ' Python ': Argv.insert (0, ' python ') command = argv Path = Os.path.  Abspath ('. ') Start_watch (Path, None)

A total of about 50 lines of code, the implementation of the debug mode of automatic reloading. Start the server with the following command:

$ python pymonitor.py wsgiapp.py

Or, add executable permissions to pymonitor.py to start the server:

$./pymonitor.py wsgiapp.py

Open a py file in the editor, modify it, save it, and look at the command line output, is not automatically restarted the server:

$./pymonitor.py wsgiapp.py [Monitor] watching directory/users/michael/github/awesome-python-webapp/www ... [Monitor] Start process python wsgiapp.py ... INFO:root:application (/USERS/MICHAEL/GITHUB/AWESOME-PYTHON-WEBAPP/WWW) 'll start at 0.0.0.0:9000 ... [Monitor] Python source file changed:/users/michael/github/awesome-python-webapp/www/apis.py[monitor] Kill process [2747] ... [Monitor] Process ended with code-9. [Monitor] Start process python wsgiapp.py ... INFO:root:application (/USERS/MICHAEL/GITHUB/AWESOME-PYTHON-WEBAPP/WWW) 'll start at 0.0.0.0:9000...try
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.