Python-module, python module download

Source: Internet
Author: User

Python-module, python module download

I. Modules

1. What is a module?

During the development of computer programs, as the program code is written more and more, the code in a file will become longer and longer, making it increasingly difficult to maintain.

In order to write maintainable code, we divide many function groups into different files, so that each file contains less code, many programming languages use this method to organize code. In Python, A. py file is called a Module ).

2. Benefits of using modules

The biggest benefit is that it greatly improves the maintainability of the Code. Second, you do not have to write the code from scratch. When a module is compiled, it can be referenced elsewhere. When writing programs, we often reference other modules, including Python built-in modules and third-party modules.

The module can also avoid conflicts between function names and variable names. Functions and variables with the same name can exist in different modules. Therefore, when writing modules, we do not have to consider that the names may conflict with other modules. However, do not conflict with the built-in function name. Click here to view all Python built-in functions.

3. Modules

Python itself has many built-in very useful modules, which can be used immediately after installation.

Built internallysysFor example, writehelloModule:

1 #! /Usr/bin/env python3 # This line of comment allows this file to run directly on Unix/Linux/Mac 2 #-*-coding: UTF-8-*-# This line of annotation indicates that the file itself uses a standard UTF-8 encoding 3 4 'a test module' # indicates the module's document annotation, the first string of any module code is considered as the module document comment 5 6 _ author _ = 'Michael liao' # Use the _ author _ variable to write the author to the file 7 8 import sys # import the built-in module sys (using the module) 9 10 11 def test (): 12 args = sys. argv # Call the argv attribute of the sys module. This variable stores all parameters of the command line in the form of a list. 13 if len (args) = print ('hello, world! ') 15 elif len (args) = print ('hello, % s! '% Args [1]) 17 else: 18 print ('too your arguments! ') 19 20 21 if _ name _ =' _ main _ ': # When we run the hello module file on the command line, the Python interpreter sets a special Variable _ name _ As _ main __, and if the hello module is imported elsewhere, the if statement fails. 22 # therefore, this if test allows a module to execute some additional code when running through the command line. The most common is to run the test. 23 test ()
Create a hello Module

4. install third-party modules

In Python, third-party modules are installed through the package management tool pip.

# Run the following command in command line mode: Pillow is the third-party module name pip install Pillow

5. Module search path

When we try to load a module, Python searches for the corresponding. py file in the specified path. If the file cannot be found, an error is returned, as shown in. import hello.

By default, the Python interpreter searches the current directory, all installed built-in modules, and third-party modules. The search path is stored insysModulepathVariable:

>>> import sys>>> sys.path['', 'C:\\Python36\\python36.zip', 'C:\\Python36\\DLLs', 'C:\\Python36\\lib', 'C:\\Python36', 'C:\\Python36\\lib\\site-packages']>>>

If you want to add your own search directory, there are two methods:

First, directly modifysys.path, Add the directory to be searched:

>>> Import sys >>> sys. path. append ('Directory to be searched ')

This method is modified at runtime and becomes invalid after running.

The second method is to set environment variables.PYTHONPATHThe content of the environment variable is automatically added to the module search path. The setting method is similar to setting the Path environment variable. Note that you only need to add your own search path. The search path of Python itself is not affected.

Ii. common modules

1. time

A. in Python, there are usually three methods to express time: Timestamp, _time, and formatted time string:

Import time # timestamp generally indicates the offset calculated in seconds from 00:00:00, January 1, January 1, 1970. We run "type (time. time ()" and return the float type. Time. time () 1493207044.6561139 # formatted time String (Format String): time. strftime ('% Y-% m-% d % x') '2017-04-26 19:47:54' # tuples (struct_time): struct_time tuples have nine elements: (year, month, day, hour, minute, second, day of the week (Monday is 0), day of the year, time zone) time. localtime () time. struct_time (tm_year = 2017, tm_mon = 4, tm_mday = 26, tm_hour = 19, tm_min = 48, tm_sec = 23, tm_wday = 2, tm_yday = 116, tm_isdst = 0)

Summary: The timestamp is the time that can be recognized by the computer; the time string is the time that people can understand; The tuples are used to operate the time.

B. Time Format Conversion

 

# Timestamp ---> structured time. localtime () time. struct_time (tm_year = 2017, tm_mon = 4, tm_mday = 26, tm_hour = 19, tm_min = 57, tm_sec = 38, tm_wday = 2, tm_yday = 116, tm_isdst = 0) time. gmtime () time. struct_time (tm_year = 2017, tm_mon = 4, tm_mday = 26, tm_hour = 11, tm_min = 57, tm_sec = 48, tm_wday = 2, tm_yday = 116, tm_isdst = 0) # structured time ---> timestamp time. mktime (time. localtime () 1493208155.0time.mktime (time. gmtime () 1493179366.0 # structured time ---> string time. strftime ('% Y-% m-% d % x', time. localtime () '2017-04-26 20:04:22 '# string time ---> structured time. strptime ('2014-04-27 ',' % Y-% m-% D') time. struct_time (tm_year = 2017, tm_mon = 4, tm_mday = 27, tm_hour = 0, tm_min = 0, tm_sec = 0, tm_wday = 3, tm_yday = 117, tm_isdst =-1)

C. asctime and ctime

 

# Structured time ---> string time. asctime (time. localtime (1493208155.0) 'wed Apr 26 20:02:35 100' # timestamp ---> string time. ctime (1493208155.0) 'wed Apr 26 20:02:35 123'

2. random

Import random # random decimal number x: 0 <x <1random. random () 0.9354224633786534 # random integer x: 1 <= x <= 10random. randint (1, 10) 1 # random integer x: 3 = <x <5random. randrange (3, 5) 3 # random return to any element in the list. choice ([1, '23', []) 1 # random return to any element of the List random. choice ([1, '23', []) [4, 5] # random return of any 2 elements in the list random. sample ([2, 'A', 33, ['B', 56], 7], 2) ['A', 7] # random decimal number x: 1 <x <3random. uniform (1.8055721248003096) # disrupt the elements in the list item = [, 9] # disrupt the previous random. shuffle (item) item [9, 3, 5, 1, 7] # after disruption

Exercise:

 

1 import random 2 3 def v_code (): 4 5 "Custom 5-digit random character verification code based on ASCII code" 6 code = '7 for I in range (5): 8 a = random. randint (48, 57) # number 0-9 9 B = random. randint (65, 90) # capital letter A-Z10 c = random. randint (97,122) # lowercase letter a-z11 d = random. choice ([a, B, c]) # returns the number 12 code = ''in the preceding three ranges randomly ''. join ([code, chr (d)]) 13 14 return code15 16 17 print (v_code ())
5-character Random verification code

3. hashlib

A. algorithm Introduction

Python hashlib provides common digest algorithms, such as MD5 and SHA1.

What is a digest algorithm? Digest algorithms are also called hash algorithms and hash algorithms. It converts data of any length into a fixed-length data string (usually expressed in hexadecimal strings) through a function ).

The digest algorithm uses the digest function f () to calculate a fixed-length digest for data of any length. It aims to find whether the original data has been tampered.

Abstract algorithms can point out whether data has been tampered with because abstract functions are a one-way function that is easy to calculate f (data), but it is very difficult to push data through digest. Furthermore, modifying the original data bit will lead to a completely different digest.

Take the common Digest algorithm MD5 as an example to calculate the MD5 value of a string:

1 import hashlib2 3 md5 = hashlib. md5 () 4 md5.update ('Hello world! '. Encode ('utf-8') 5 print (md5.hexdigest () 6 7 # result: 8 #86fb269d1_d2c85f6e0468ceca42a20

If the data volume is large, you can call update () multiple times in multiple parts. The calculation result is the same:

1 import hashlib2 3 md5 = hashlib. md5 () 4 md5.update ('hello '. encode ('utf-8') # Note: there is a space 5 md5.update ('World! '. Encode ('utf-8') 6 print (md5.hexdigest () 7 8 # result: 9 #86fb269d1_d2c85f6e0468ceca42a20

MD5 is the most common Digest algorithm, which is very fast. The generated result is a fixed 128-bit byte, which is usually represented by a 32-bit hexadecimal string. Another common Digest algorithm is SHA1. Calling SHA1 is similar to calling MD5:

1 import hashlib 2 3 sha1 = hashlib. sha1 () 4 sha1.update ('hello'. encode ('utf-8') #5 sha1.update ('World! '. Encode ('utf-8') 6 print (sha1.hexdigest () 7 8 sha2 = hashlib. sha1 () 9 sha2.update ('Hello world! '. Encode ('utf-8') 10 print (sha2.hexdigest () 11 12 # result: 13 # response # d3486ae9136e7856bc42212316ea797094475802

The result of SHA1 is 160 bits, usually expressed in a 40-bit hexadecimal string. SHA256 and SHA512 are more secure than SHA1, but the more secure the algorithm is, the longer the digest length.

B. Algorithm Application

Any website that allows users to log on will store the user name and password for user logon. How to store usernames and passwords? The method is to save it to the database table:

name    | password--------+----------michael | 123456bob     | abc999alice   | alice2008

If the user password is stored in plain text, and the database leaks, the passwords of all users will fall into the hands of hackers. In addition, website O & M personnel can access the database, that is, they can obtain the passwords of all users. The correct password saving method is not to store the user's plaintext password, but to store the digest of the user's password, such as MD5:

username | password---------+---------------------------------michael  | e10adc3949ba59abbe56e057f20f883ebob      | 878ef96e86145580c38c87f0410ad153alice    | 99b1c2188db85afee403b1536010c2c9

Considering this situation, many users prefer simple passwords such as 123456,888888 and password. Therefore, hackers can calculate the MD5 values of these frequently used passwords in advance to obtain a reverse table:

'e10adc3949ba59abbe56e057f20f883e': '123456''21218cca77804d2ba1922c33e0151105': '888888''5f4dcc3b5aa765d61d8327deb882cf99': 'password'

In this way, you do not need to crack the password. Instead, you only need to compare the MD5 of the database, and the hacker will obtain the user account using the common password.

Do not use a simple password. However, can we enhance protection for simple passwords in programming?

Because the MD5 values of common passwords are easily calculated, make sure that the stored user passwords are not the MD5 values of common passwords that have been calculated, this method is implemented by adding a complex string to the original password, commonly known as "adding salt ":

hashlib.md5("salt".encode("utf8"))

The MD5 password processed by Salt is hard to reverse-push the plaintext password through MD5 even if the user enters a simple password as long as it is not known by hackers.

However, if two users use the same simple password, such as 123456, two identical MD5 values will be stored in the database, which indicates that the passwords of the two users are the same. Is there a way for users with the same password to store different MD5 numbers?

If you cannot modify the login name, you can calculate the MD5 value by using the login name as a part of the Salt, so that users with the same password can also store different MD5 values.

Abstract algorithms are widely used in many places. Note that the digest algorithm is not an encryption algorithm and cannot be used for encryption (because digest reverse plain text cannot be used). It can only be used to prevent tampering, however, its one-way computing feature determines that the user password can be verified without storing the plaintext password.

4. OS

1 ''' 2 OS. getcwd () obtains the current working directory, that is, the directory path where the current python script Works 3 OS. chdir ("dirname") changes the current script working directory, which is equivalent to cd 4 OS in shell. curdir returns the current directory :('. ') 5 OS. pardir: Get the string name of the parent directory of the current directory :('.. ') 6 OS. makedirs ('dirname1/dirname2') can generate multi-layer recursive directory 7 OS. removedirs ('dirname1') if the directory is empty, delete it and recursively go to the upper-level directory. If the directory is empty, delete it, and push 8 OS. mkdir ('dirname') generates a single-level Directory, which is equivalent to mkdir dirname 9 OS 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 dirname10 OS in shell. listdir ('dinam E ') list all files and subdirectories in the specified directory, including hidden files, and print 11 OS in list mode. remove () delete a file 12 OS. rename ("oldname", "newname") rename the file/directory 13 OS. stat ('path/filename ') obtains the file/directory information 14 OS. sep outputs the specific path Separator of the operating system. In win, it is "\", and in Linux it is "/" 15 OS. linesep outputs the line terminator used by the current platform. In win, it is \ t \ n, and in Linux it is \ n 16 OS. pathsep outputs the string win for splitting the file path; and 17 OS for Linux. name output string indicates that the current platform is used. Win-> 'nt '; Linux-> 'posix' 18 OS. system ("bash command") runs the shell command and 19 OS is displayed directly. environ obtains the system environment variable 20 OS. path. abspath (path) returns the path normalized absolute path 21 OS. path. split (path) splits the path into two groups: Directory and file name. 22 OS is returned. path. dirname (path) returns the path directory. In fact, the first element 23 OS. path. basename (path) of OS. path. split (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) is 24 OS. path. exists (path) returns True if path exists. Returns False25 OS if path does not exist. path. isabs (path) returns True26 OS if path is an absolute path. path. isfile (path) returns True if path is an existing file. Otherwise, False27 OS. path. isdir (path) is returned. If path is an existing Directory, True is returned. Otherwise, False28 OS 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 of the file or directory pointed to by path 30 OS. path. getmtime (path) returns the last modification time of the file or directory pointed to by path 31 OS. path. getsize (path) returns the size of the path '''

5. sys

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. the name of the operating system platform returned by platform

 

 

References:

1. http://www.cnblogs.com/yuanchenqi/articles/6766020.html

2. http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431845183474e20ee7e7828b47f7b7607f2dc1e90dbb000

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.