How does python reload module instance parsing and python reload module?

Source: Internet
Author: User

How does python reload module instance parsing and python reload module?

This article first introduces the concept of a module in Python. It talks about a module that usually consists of multiple modules. Then, it analyzes the heavy load of modules through specific examples. The details are as follows.

A module is a core concept of the Python program architecture. A large program is usually presented in the form of multiple module files. A module is designed as a master file or a top-level file to start the entire Python program. Each Python source code file suffixed with. py is a module. Other files can read the content of this module through "import. In general, a module is the encapsulation of variable names. For example, write a module test. py, which contains two variable names: name and age.

name='Aidan' age=27 

Then, run the following command in the Python command line:

import test print(test.name, test.age) 

Expected result: Aidan 27

The dir (modelname) function can be used to obtain the available variable names in the module. It contains some Python built-in variable names such as '_ doc _ and _ file __'.
A Python program is usually composed of multiple modules and connected through import.Each module file is a namespace and the variable names of other module files cannot be seen, unless the file is imported through import orfrom model import varibleImport a variable. This avoids variable naming conflicts, because each module is an independent namespace, similar to a function and its local variables in C language.

In essence, "import" is to load the content of another file in one file, so that another file can be used in the external world. The command isimport name.py. The import only works for the first execution of each session. Subsequent import of the same file is invalid even if the file is changed, this is because the file is compiled into bytecode during the first import. The import module must know the detailed path of the module (file search can be performed through sys. the PYTHONPATH variable in path specifies all directories to be searched. Therefore, in order to be simple, put all the files to be imported in the same directory.

If you want to run the same file multiple times in the same session (or the file has changed and must be reloaded), you need to call the "overload" function-reload (name ), before calling the reload function, ensure that the module has been imported successfully through import. See the differences between "function" reload () and "statement" import,Reload () is a function and a parameter is the file name of the imported file module. import is a statement without parentheses. The Python overload function allows users to edit and improve code modules during interaction. Therefore, to ensure that the latest code is run, reload () is used first ().

During the debugging of flask, If we modify the file, the server will be restarted without stopping the server and restarting it. This hides an overloaded mechanism.

The following is a simple example to explain how python works.Reload a module

Create a file named reloadsetting. py with the following content:

#coding=utf-8 ''''' Created on 2016-3-25  @author: Administrator '''  msg = 'change it ' 

Create a new file named reloaddemo. py with the following content:

# Coding = UTF-8 ''' Created on 2016-3-25 @ author: Administrator ''' import threading import reloadsetting import sys, OS, time def printworker (): while True: time. sleep (1) print reloadsetting. msg def auto_reload (): while True: mod = ["reloadsetting"] # the need reload modules for mod in mod: try: module = sys. modules [mod] except: continue # obtain the file name filename = module. _ file _ # The file ending with pyc is generated only when it is loaded for the first time. Therefore, even if we modify the file, the modification time does not change if filename. endswith (". pyc "): filename = filename. replace (". pyc ",". py ") # obtain the last file modification time mod_time = OS. path. getmtime (filename) # module. the module information is saved in _ dict _. For details, refer to the globals function if not "loadtime" in module. _ dict __: module. loadtime = 0 # first load's time 1 * try: # if the modification time is later than the last loading time, load the if mod_time> module again. loadtime: reload (module) failed T: pass module. loadtime = mod_time time. sleep (1) if _ name _ = '_ main _': t_reload = threading. thread (target = auto_reload) t_reload.start () t_reload2 = threading. thread (target = printworker) t_reload2.start ()

We started to run reloaddemo. py. A thread continuously prints the msg in the reloadsetting module, and a thread continuously tries to reload the reloadsetting module. During the running process, the msg content in the reloadsetting module will be modified quickly, and the printed content will change accordingly. You may worry that if you accidentally write the wrong code during the modification, for example, if msg is deleted or written as msg =, and no value is assigned at the end, isn't the overload a failure? This worry is redundant, even if the reloadsetting module has an error, no error will occur when calling the reload function. The module is still in the status after the last effective reload. Do not believe it. You can try it.

Summary

The above is all the content about how to reload the module instance parsing in python. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.