Use Python to load only modified processes on the server

Source: Internet
Author: User
This article mainly introduces how to use Python to implement only modifying processes in the server, including using watchdog to detect file changes, the implementation fully reflects the flexibility of Python as a dynamic language. it is strongly recommended! For more information, see. now, we have fully built a Web App framework. the process from the back-end API to the front-end MVVM has passed.

Before continuing to work, note that every time you modify the Python code, you must Ctrl-C on the command line to stop the server and then restart the server to make the change take effect.

In the development phase, code is modified and saved dozens of times every day. it is very troublesome to manually save the code each time, seriously reducing our development efficiency. Is there a way for the server to automatically reload the code after detecting the modification?

Django's development environment can be automatically reloaded in Debug mode. if the server we write can also implement this function, it can greatly improve the development efficiency.

It is a pity that Django has not provided this function independently and won't be able to enjoy it without using Django. what should I do?

In fact, Python itself provides the function of re-loading modules, but not all modules can be re-loaded. Another idea is to detect code changes under the www Directory. once there are changes, the server will be automatically restarted.

Based on this idea, we can compile a helper program pymonitor. py to start wsgiapp. in the www directory. if the py process is killed and restarted, the server process is automatically restarted.

To monitor changes in directory files, we do not need to manually scan them regularly. The Python third-party library watchdog can monitor changes in directory files using the operating system API and send notifications. We first install it with easy_install:

$ easy_install watchdog

Watchdog is used to receive File change notifications. if the file is a. py file, the wsgiapp. py process is automatically restarted.

Use the subprocess that comes with Python to start and terminate the process, and redirect the input and 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 FileSystemEventHandlerdef log(s):  print '[Monitor] %s' % sclass MyFileSystemEventHander(FileSystemEventHandler):  def __init__(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()command = ['echo', 'ok']process = Nonedef kill_process():  global process  if process:    log('Kill process [%s]...' % process.pid)    process.kill()    process.wait()    log('Process ended with code %s.' % process.returncode)    process = Nonedef start_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 KeyboardInterrupt:    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)

With a total of about 50 lines of code, the Debug mode is automatically reloaded. Run the following command to start the server:

$ python pymonitor.py wsgiapp.py

Or add the executable permission to pymonitor. py to start the server:

$ ./pymonitor.py wsgiapp.py

Open a py file in the editor, modify it, and save it. check whether the command line output automatically restarts 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) will 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) will start at 0.0.0.0:9000...Try

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.