Python learning path: day6; python path: day6
Outline:
1. Reflection
Methods: getattr, delattr, setattr, hasattr
_ Import __()
_ Import _ () Note
2. Special variables in the module
_ Doc __
_ Cached __
_ File __
_ Name __
_ Package __
3. sys module
Progress bar
4. OS Module
Reflection
Operate (Search/check/delete/set) members (functions) in objects (modules) in the form of strings to reflect
Methods used: getattr, delattr, setattr, hasattr
A Routing System with a forged web Framework
Commons. py file
Commons. pydef login (): print ("Logon page") def logout (): print ("Exit page") def home (): print ("Homepage ")
Index. py file
Import commons # Call commons module def run (): url = input ("Enter the url to access:") "url = string type, if url = "login" commons. url () Obviously, this is wrong, because executing commons will go to him to find whether there is a url function. If not, an error will be reported directly to use the string form to go to the object (module) member (function), reflection "" # setattr () # delattr () if hasattr (commons, url ): # url = string. Now, the url is equivalent to a function. The input function uses hasattr to determine whether the function exists. The return value is True or False func = getattr (commons, url) # Use getattr to obtain this function, for example, url = login. That is to say, now (func = commo Ns. login) func () # Then run the following func to execute the else: print ("404") function in commons # If hasattr does not check, execute the following command: 404if _ name _ = '_ main _': # _ name _ is the name of the current module, when the module is directly run, the module name is _ main __. This statement means that when the module is directly run, the following code block will be run. When the module is imported, the code block will not be run. Run () Output: Enter the url to access: login Page
We can see from the above that we can only access one module. If we add one module, we need to continue adding it in import. Of course, python also thought about this problem, so import can also pass strings.
A small test:
# File: commons. pydef login (): print ("Logon page") def logout (): print ("Exit page") def home (): print ("Homepage") # file: import_test.pyobj = _ import _ ("commons") # input the string obj. login () obj. logout () obj. home () Output: Exit from the logon page.
_ Import __():
File: manager. pydef order (): print ("order page") file: commons. pydef login (): print ("Logon page") def logout (): print ("Exit page") def home (): print ("Homepage") # file: index. py # has several bugs, such as two // or no/or the module name is out of order. Of course, this is just a Reflection Experiment def run (): URL = input ("Enter the url to access:") imp, url = URL. split ("/") # because it is a web browser, It is differentiated by/. The previous one is assigned to imp, and the subsequent one is assigned to url obj = _ import _ (imp) # obtain the input module name if hasattr (obj, url): # determine whether this module and function name exist, return True, False func = getattr (obj, url) # obtain the modules and functions, including obj = commons and rul = login. Then they are equal to commons. login func () else: print ("404") if _ name _ = '_ main _': run () Output: Enter the url to access: on the manager/order page, enter the url to access: commons/home.
_ Import _ () Note:
What should I do if this happens? Of course, do not think (obj = _ import _ ("lib." + string,Of course the answer is not.
Solution:
String = "commons" obj = _ import _ ("lib. "+ string) # Only the lib module is returned, but not the lib module. commons module print (obj) # output # <module 'lib' (namespace)> string = "commons" obj = _ import _ ("lib. "+ string, fromlist = True) # When fromlist = True is added, lib is returned. commonsprint (obj) # output # <module 'lib. commons 'from 'd: \ materials \ common \ python \ day6 \ reflex \ reflex_import_test \ lib \ commons. py'>
Special variables in the module
Import OS # _ doc __# _ cached __# _ file __# _ name _ "comment" print (_ doc __) # obtain the comment using "" in the entire py file (for no eggs) # _ cached _ seems to have no eggs with print (_ file __) # Return the path print (OS. path. abspath (_ file _) # obtain the absolute path of the current py file # OS. path. dirname () # returns print (OS. path. dirname (OS. path. abspath (_ file _) # returns the absolute path print (_ package _) at the upper level of the current py file # returns the package of the current py file; print (OS. _ package _) # only when the current file is executed, the special Variable _ name _ = "_ main _" # _ name __ Def run (): passif _ name _ = '_ main _': # _ name _ is the name of the current module, when the module is directly run, the module name is _ main __. This statement means that when the module is directly run, the following code block will be run. When the module is imported, the code block will not be run. Run ()
Sys module
Provides operations related to the Python Interpreter:
"Sys. argv command line parameter List. The first element is the program path sys. exit (n) exit the program. exit (0) sys when the program Exits normally. obtain the version information of the Python interpreter sys. the maximum Int value of maxint sys. path: return the search path of the module. during initialization, use the value of the PYTHONPATH environment variable sys. platform returns the name of the operating system platform sys. sys. stdout output related sys. stderror error related """
Progress bar:
import sysimport timedef view_bar(num, total): rate = num / total rate_num = int(rate * 100) r = '\r%s%d%%' % ("=" * num, rate_num) sys.stdout.write(r) sys.stdout.flush()if __name__ == '__main__': for i in range(0, 100): time.sleep(0.1) view_bar(i, 100)
OS Module
OS. getcwd () obtains the current working directory, that is, the operating directory path of the current python script. chdir ("dirname") changes the current script working directory, which is equivalent to cdos in shell. curdir returns the current directory :('. ') OS. pardir: Get the string name of the parent directory of the current directory :('.. ') OS. makedirs ('dir1/dir2') can generate a multi-layer recursive directory OS. removedirs ('dirname1') if the directory is empty, it is deleted and recursive to the upper-level directory. If the directory is empty, it is deleted and OS is pushed accordingly. mkdir ('dirname') generates a single-level Directory, which is equivalent to mkdir dirnameos in shell. rmdir ('dirname') deletes a single-stage empty directory. If the directory is not empty, it cannot be deleted. An error is returned, which is equivalent to rmdir dirnameos in shell. listdir ('dirname') lists all files and subdirectories in a specified directory, including hidden files, and prints OS in list mode. r Emove () deletes a file OS. rename ("oldname", "new") rename the file/directory OS. stat ('path/filename ') to obtain the file/directory information OS. the specific path Separator of the sep operating system. The path separator is "\" in win, and the path separator is "/" in Linux. linesep: The line terminator used by the current platform. The line terminator is \ t \ n in win, and the line terminator is \ n in Linux. pathsep is the string OS used to split the file path. the name string indicates the current platform. Win-> 'nt '; Linux-> 'posix' OS. system ("bash command") runs the shell command to directly display the OS. environ obtains the OS environment variable. path. abspath (path) returns the absolute path OS of path normalization. path. split (path) splits the path into two groups: Directory and file name, and returns OS. path. dirname (path) returns the path directory. In fact, the first element OS. path. split (path) of OS. path. basename (path) returns the final file name of path. If the path ends with a slash (/) or slash (\), a null value is returned. That is, OS. path. the second element of split (path), OS. path. exists (path) returns True if path exists. Returns Falseos if path does not exist. path. isabs (path) returns Trueos if path is an absolute path. path. isfile (path) returns True if path is an existing file. Otherwise, Falseos. path. isdir (path) is returned. If path is an existing Directory, True is returned. Otherwise, Falseos is returned. path. join (path1 [, path2 [,...]) if multiple paths are combined, the parameters before the first absolute path are ignored. path. getatime (path) returns the last access time OS of the file or directory pointed to by path. path. getmtime (path) returns the last modification time of the file or directory pointed to by path.
Hashlib Encryption
Used for encryption-related operations, instead of the md5 module and sha module, mainly provides SHA1, sha1_, SHA256, SHA384, SHA512, MD5 Algorithm
Import hashlib ######### md5 ######## obj = hashlib. md5 () obj. update (bytes ("123", encoding = "UTF-8") # perform md5 encryption on 123 and use UTF-8 encoding result = obj. hexdigest () # obtain the md5 value print (result) # From the above we can see that if the same password is 123, then the generated md5 is the same as the above, to solve this bug, you can use the following method obj = hashlib. md5 (bytes ("admin", encoding = "UTF-8") # encrypt the admin and then execute the following encrypted obj. update (bytes ("123", encoding = "UTF-8") # perform md5 encryption on 123 and use UTF-8 encoding result = obj. hexdigest () # obtain the md5 value print (result) # From the two columns above, we can see that the second column also has a bug, because it is equivalent to encrypting admin123 ######## sha1 ######## hash = hashlib. sha1 () hash. update (bytes ('admin', encoding = 'utf-8') print (hash. hexdigest () ######### sha256 ######## hash = hashlib. sha256 () hash. update (bytes ('admin', encoding = 'utf-8') print (hash. hexdigest () ######### sha384 ####### hash = hashlib. sha384 () hash. update (bytes ('admin', encoding = 'utf-8') print (hash. hexdigest () ######### sha512 ######## hash = hashlib. sha512 () hash. update (bytes ('admin', encoding = 'utf-8') print (hash. hexdigest () # There is an hmac module built in python, which further processes the key and content we create and then encrypts import hmach = hmac. new (bytes ('898oafs09f', encoding = "UTF-8") h. update (bytes ('admin', encoding = "UTF-8") print (h. hexdigest ())
Re Module
In python, the re module provides operations related to regular expressions.
Character:
. Match any character except linefeed
\ W matches letters, numbers, underscores, and Chinese characters
\ S matches any blank space character
\ D matching number
\ B matches the start or end of a word
^ Match the start of a string
$ End of matching string
Times:
* Repeated zero or more times
+ Repeat once or more times
? Zero or one repetition
{N} repeated n times
{N,} repeat n times or more times
{N, m} repeat n to m times
Re. match starts from the starting position. If the match is successful, an object is returned. If the match is not successful, Nonere is returned. search browses the entire string to match the first one. If no matching is successful, Nonere is returned. findall obtains the list of non-repeated matches. If there is a group, it is returned in the form of a list, and each match is a string. If there are multiple groups in the model, it is returned in the form of a list, and each match is the ancestor; re. split uses the matched characters as the list separator re. sub replaces the matched string at the specified position
Slashes
Like most programming languages, regular expressions use "\" as escape characters, which may cause backlash troubles. If you need to match the character "\" in the text, four Backslash "\" will be required in the regular expression expressed in programming language "\\\\": the first two and the last two are used to convert them into backslashes in the programming language, convert them into two backslashes, and then escape them into a backslash in the regular expression. The native string in Python solves this problem well. The regular expression in this example can be represented by r. Similarly, "\ d" matching a number can be written as r "\ d ". With the native string, you no longer have to worry about missing the backslash, and the written expression is more intuitive.
Common Regular Expressions
IP: ^ (25 [0-5] | 2 [0-4] \ d | [0-1]? \ D? \ D) (\. (25 [0-5] | 2 [0-4] \ d | [0-1]? \ D? \ D) {3} $ mobile phone number: ^ 1 [3 | 4 | 5 | 8] [0-9] \ d {8} $ Email: [a-zA-Z0-9 _-] + @ [a-zA-Z0-9 _-] + (\. [a-zA-Z0-9 _-] +) +