Python Module 2: python Module

Source: Internet
Author: User
Tags add time

Python Module 2: python Module

10 common modules:
1> OS module:
OS. getcwd (): Get the current working directory, that is, the directory path of the current python script;
OS. chdir ("dirname"): change the working directory of the current script, which is equivalent to cd in shell;
OS. curdir: the current directory is returned :('.')
OS. pardir: gets the string name of the parent directory of the current directory :('..')
OS. makedirs ('dirname1/dirname2'): multiple-layer recursive directories can be generated;
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 so on;
OS. mkdir ('dirname'): generate a single-level Directory, which is equivalent to mkdir dirname in shell;
OS. rmdir ('dirname'): deletes a single-level directory. If the directory is not empty, it is deleted;
OS. listdir ('dirname'): lists all files and subdirectories in a specified directory;
OS. remove: delete an object;
OS. rename ("oldname", "newname"): rename a file/directory;
OS. stat ('path/filename '): obtains the file/directory information;

OS. sep: Specifies the path delimiter of the output operating system. In win, it is \, and in Linux it is/.
OS. linesep: output the line terminator used by the current platform. The line terminator is "\ t \ n" in win, and the line terminator is "\ n" in Linux ";
OS. pathsep: output the string used to split the file path;
OS. name: the output string indicates the current platform, win-> 'nt '; Linux-> 'posix ';
OS. system ("bash command"): runs the shell command and displays it directly;

OS. popen ("bash command"). read (): stores the shell command execution results;

OS. environ: obtains system environment variables;
OS. path. abspath (path): returns the absolute path of path normalization;
OS. path. split (path): splits the path into two groups of directories and file names and returns them;
OS. path. dirname (path): returns the path Directory, which is actually the first element of OS. path. split (path;
OS. path. basename (path): returns the last file name of the path.
OS. path. exists (path): If the path exists, True is returned. If the path does not exist, false is returned;
OS. path. isabs (path): returns True if path is an absolute path;
OS. path. isfile (path): If path is an existing file, True is returned; otherwise, false is returned;

      

OS. path. isdir (path): If path is an existing Directory, True is returned; otherwise, false is returned;
OS. path. join (path1 [, path2 [,...]): returns the first absolute path after combining multiple paths;
OS. path. getatime (path): returns the last access date of the file or directory pointed to by path;
OS. path. getmtime (path): returns the last modification date of the file or directory pointed to by path;

2> sys module:
Sys. argv: list of command line parameters. The first element is the program itself;
Sys. exit (n): exit the program. exit (0) when the program Exits normally );
Sys. version: get the version information of the python interpreter;
Sys. maxint: The maximum int value;
Sys. path: return the search path of the module;
Sys. platform: return the name of the operating platform;
Sys. stdout. write ('Please: '): Used as a progress bar;
Val = sys. stdin. readline () [:-1]

3> shutil module: Advanced file, folder, and compressed package processing module;
* *** Shutil calls ZipFile and TarFile to process the compressed package;

    

Shutil. copy. fileobj (fsrc, fdst [, length]): copy the file content to another file, which can be partial content;
Shutil. copyfile (src, dst): copy an object;
Shutil. copymode (src, dst): only copy permissions; content, group, and users remain unchanged;
Shutil. copystat (src, dst): Copy status information, including mode bits, atime, mtime, flags;
Shutil. copy (src, dst): copy objects and permissions;
Shutil. copy2 (src, dst): copy file and status information;
Shutil. ignore_patterns (* patterns ):
Shutil. copytree (src, dst, symlinks = False, ignore = None): Recursively copies objects;
Shutil. rmtree (path [, ignore_errors [, onerror]): recursively deletes an object;
Shutil. move (src, dst): recursively move a file;
Shutil. make_archive (base_name, format,...): Create a compressed package and return the file path;

Base_name: the file name of the compressed package. It can also be the path of the compressed package. If it is only the file name, it is saved to the current directory; otherwise, it is saved in the specified path;
Format: zip, tar, bztar, and gztar ";

4> shelve module: it is a simple k. v stores memory data through the file persistence module and can persist any python supported by pickle.
Data format;
Persistence:

Read:

        

5> xml processing module:
Xml is a protocol for data exchange between different languages or programs. It is similar to json, but json is easier to use. However, before json is born, you can only use xml, so far, many traditional companies, such as the financial industry, mainly use xml interfaces. xml distinguishes data structures through <> nodes;
Xml document content:

        

Xml node traversal:

Modify an xml node:

        

Delete an xml node:

        

6> configparser (name in 3) module: ---- ConfigParser (name in 2)
Definition: used to generate and modify common configuration documents;
Write the configuration file:

        

Read the configuration file:

Delete some content in the configuration file:

Add configuration file content:

          

          

Rewrite the configuration file content:

          

          

Delete the content of an element in the configuration file:

            

7> hashlib module: used for encryption-related operations. 3 replaces the md5 module and sha module, and mainly provides SHA1, shaloud, SHA256, SHA384, SHA512, and MD5 algorithms; the entered content is the same, and the encrypted result is the same; the encrypted content cannot be reversed;
Md5 encryption example:

        

Example of sha512 encryption:

        

For encryption, python also has an hmac module that processes and encrypts the key and content that we create internally;

        

8> subprocess module: Used to interact with the operating system, execute commands, and execute scripts, replacing OS. system; 3 is subprocess. run (), 2 is subprocess. call ();
Run the command without parameters:

Run the command with parameters:

          

          

Get the real result of executing the command:

          

Check the execution status return code. If the code is correct, 0 is returned. If the code is incorrect, an exception is thrown:

          

Terminal input commands can be divided into two types:
Input to get the output: for example, ifconfig
Input to a certain environment, dependency and re-input, such as: python
Command example for interaction: (create another child process in the parent process)

            

9> logging module:
Many programs have the need to record logs, and the information contained in the logs is both normal program access logs, and may have errors, warnings, and other information output, the logging module of python provides a standard log interface, which stores logs of various formats. logs of logging can be divided into debug (), info (), warning (), error () and critical (): 5 levels;
Print log information:

        

Write logs to a file: (this level and above will only be stored after the set level)

        

Add time to the log:

          

          

Print logs in both the screen and log file:

          

          

            

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.