2. Python Module

Source: Internet
Author: User
Tags create directory exit in stdin

1. Logging module

Log is our key tool to troubleshoot problems, write log records, and when we have problems, you can quickly locate the code range to modify.

Python provides developers with a good log module, the following describes the logging module:

First, let's look at an example:

Import logging

Logging.debug (' This is Debug message ')

Logging.info (' This is Info message ')

Logging.warning (' This is warning message ')

Logging.error (' This is error message ')

Logging.critical (' This is critical message ')

Results:

WARNING:root:This is WARNING message

ERROR:root:This is error message

CRITICAL:root:This is CRITICAL message

By default, logging prints logs to the screen

The log level size relationship is:

CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET, and of course you can define the log level yourself.

DEBUG: Detailed information, usually appearing only on diagnostic issues.

INFO: Make sure everything works as expected

WARNING: A warning, there may be some unexpected things happening, or indicate some problems in the near future (for example. Disk space is low "), the software can work as expected

ERROR: A more serious problem, the software does not perform some functions

CRITICAL: A serious error that indicates that the program itself may not continue to run

Default logging The default log level is info, generally basically all programs are this level, help us to troubleshoot problems, but when there is a problem, we can not locate the problem, in many cases we need to raise the log level to the debug level.

How to raise the log level:

Configure the output format and mode of log by Logging.basicconfig function

Import logging

Logging.basicconfig (level=logging. DEBUG, format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ', datefmt= '%y/%m/%d%h:%m:%s ', Filename= ' Myapp.log ', filemode= ' W ')

Logger = Logging.getlogger (__name__)

Logging.debug (' This is Debug message ')

Logging.info (' This is Info message ')

Logging.warning (' This is warning message ')

Logging.error (' This is error message ')

Logging.critical (' This is critical message ')

Results:

A new Myapp.log file has been added to the current file with the following contents:

2017/11/10 21:17:42 Read.py[line:12] Debug this is debug message

2017/11/10 21:17:42 Read.py[line:13] Info This is INFO message

2017/11/10 21:17:42 Read.py[line:14] WARNING This is WARNING message

2017/11/10 21:17:42 Read.py[line:15] Error This is ERROR message

2017/11/10 21:17:42 Read.py[line:16] CRITICAL This is CRITICAL message

Explain:

Mainly through the Logging.basicconfig function, now let's introduce the use of this function parameter:

Level: Sets the log levels by default to logging. WARNING

filename: Specifies the log file name.

FileMode: Same as file function, specify open mode of log file, ' W ' or ' a '

Format: Specifies the formats and contents of the output, format can output a lot of useful information, as in the example above:

% (levelname) S: Print log level name

% (filename) s: Prints the current name of the executing program

% (funcName) s: Print the current function of the log

% (Lineno) d: Print the current line number of the log

% (asctime) s: Time to print logs

% (thread) d: Print thread ID

% (process) d: Print process ID

% (message) s: Print log information

datefmt: Specify time format, same as Time.strftime ()

Stream: Specifies the output stream that will log, can specify output to Sys.stderr,sys.stdout or file, default output to Sys.stderr, stream is ignored when stream and filename are specified simultaneously

Logging.getlogger (__name__):

Create a Log object:

Returns a logger instance that returns root logger if no name is specified.

As long as name is the same, the returned logger instances are the same and only one, that is, the name and the logger instance are one by one corresponding.

This means that there is no need to pass logger instances in each module.

As long as you know name, you can get the same logger instance.

Logging.getlogger (__name__) __name__ in the above example refers to __main__.


2.os Module

OS module is also a commonly used in our work of a module, through the OS module call system commands, get the road, get the type of operating system, etc. are the use of the module.

Let's look at the OS module below.

(1) System type acquisition via OS

Import OS

Print (Os.name)

This is the type of view of our system:

If it is a Windows system, Os.name = ' NT ';

If it is a Linux system os.name = ' posix ';

Different operating systems are commands that may not be the same.

So before using the system command, we need to determine whether the system is a Linux system or a Windows system.

(2) Execute system command

Using Python to substitute system commands

Import OS

Os.system (' ipconfig ')

content=os.popen(' ipconfig '). Read ()

Print (content)

Explain:

The code calls the Windows system's ipconfig command, and Ipconfig is used to view the Windows system IP.

Os.system (' ifconfig ') only invokes the system's commands, but what happens when we need to get the results of the final execution of the system command?

At this point we use the Os.popen () method,os.popen ( ) Returns a file object, and we can get the final result of the final system command by File.read () .

(3) directory and file related operations

① get the path to the current directory

Import OS

Print (OS.GETCWD ())

② listing files for the current directory

Print (Os.listdir (OS.GETCWD ()))

③ Switching directories

Os.chdir (' d: ')

④ list files in the C:\Python27 directory

Print (Os.listdir (' C:\Python27 '))

⑤ creating the ABC directory under the current directory

Os.mkdir (' abc ')

⑥ Delete the 1.txt file in the current directory (if the file does not exist, it will be an error)

Os.remove (' 1.txt ')

⑦ print operating system delimiter, Linux system delimiter \n,windows system delimiter \r\n,mac system delimiter \ r

Print (OS.LINESEP)

⑧ in the current directory splicing field, do not create # E:\test\abc.txt file

Print (Os.path.join (OS.GETCWD (), ' abc.txt '))

Return # E:\test\abc.txt

Print (Os.path.islink (OS.GETCWD ()))

Return # False

⑨ to separate the last file name and directory

path1 = Os.path.join (OS.GETCWD (), ' abc.txt ')

Print (Os.path.split (path1))

Return # (' E:\\test ', ' abc.txt ')

⑩ to separate the first section and the back

Print (Os.path.splitdrive (path1))

Return # (' E: ', ' \\test\\abc.txt ')

(11) Separate the directory file name and suffix name

Print (Os.path.splitext (path1))

Return # (' E:\\test\\abc ', '. txt ')

(12) If the current directory exists AAA directory, not created, currently does not exist AAA directory, create AAA directory

If not os.path.exists (R ' E:\test\aaa '):

Os.makedirs (R ' E:\test\aaa ')

(13) Get the directory of E:\test\test.py files

Print (Os.path.dirname (R ' E:\test\test.py '))

Return # E:\test

Explain:

1,OS.GETCWD () Get the current system program of the directory work hard

2,os. ChDir (' target directory ') switch to target directory

3,os.listdir (' string directory ') lists all files in the string directory

4,os.makedirs (' directory ') Create directory

5,os.remove (' 1.txt ') Delete file, error when file does not exist

6,OS.LINESEP print operating system delimiter, Linux system delimiter \n,windows system delimiter \r\n,mac system delimiter \ r

7,os.path.join (OS.GETCWD (), ' AAA ', ' BBB ', ' CCC ') stitching out multilevel directory: E:\TEST\AAA\BBB\CCC

8,os.path.exists (' directory ') to determine if the directory exists

9,os.path.split (' file or directory ') separates the last directory or file from the previous directory and returns a tuple

10,os.path.splitext (' file ') separates the file suffix name from the front and returns a tuple


3.commands modules are only used in the Linux shell mode

In our usual code word, often need to call the system script or system commands to solve many problems;

A very useful module command, you can call the system commands through Python;

Commands is a module that provides support for the use of Shell commands in a Linux system environment;

There are three ways to call the system command module: CMD for system commands.

(1) commands.getoutput (CMD)

Function: Returns only the result of executing the shell command

#!/usr/bin/env python

#-*-Coding:utf-8-*-

Import commands

cmd = ' ls/home/admin '

A = Commands.getoutput (cmd)

Print (Type (a))

Print (a)

Results:

<type ' str ' >

Nginx.conf

test.py

(2) commands.getstatusoutput (CMD)

Function: In the above we execute the shell command, our shell command may perform an error, or exit abnormally, we will have a condition to determine what the shell finally executes, commands.getstatusoutput (CMD) The returned result has two values.

#!/usr/bin/env python

#-*-Coding:utf-8-*-

Import commands

cmd = ' ls/home/admin '

c = commands.getstatusoutput (cmd)

Print (Type (c))

Status, Output = Commands.getstatusoutput (cmd)

Print (status)

Print (output)

Print (type output)

Results

<type ' tuple ' >

0

Nginx.conf

test.py

<type ' str ' >

Explain:

The return result of Commands.getstatusoutput (CMD) is a tuple, the first value is the result of the shell execution, if the shell executes successfully, returns 0, otherwise, is not 0;

The second is a string that is the result of the execution of our shell command, and Python is copied to status and output in one by one ways.



4. SYS module

(1) getting the program's parameters through the SYS module

Import Sys

Print (' argv[0] = {0} argv [1] = {1} '. Format (sys.argv[0], sys.argv[1]))

Perform:

Python test.py Hello

Results:

Argv[0] = e:/test/test.py argv [1] = Hello

Explain:

As in other languages, the SYS module of Python defaults to the first parameter, which is the program's province by default, and the parameter that is followed by the code from the second parameter, which can be obtained by sys.arg[n].


(2) sys.stdin \ stdout \ stderr

Features: stdin, stdout, and stderr variables contain stream objects that correspond to standard I/O streams.

If you need more control over the output, and print does not meet your requirements, they are what you need.

You can also replace them, so you can redirect output and input to other devices, or handle them in a non-standard way

(2.1) Sys.stdout and print

When we call print obj in Python, the sys.stdout.write (obj+ ' \ n ') is actually called, print prints the content you want to the console, and then appends a newline character, and print calls The Write method of the sys.stdout.

The following two lines are in fact equivalent:

Import Sys

Sys.stdout.write (' Hello\ n') #默认不加换行符, add line breaks manually if you need to wrap.

print ' Hello '

(2.2) Sys.stdin and Raw_input

Import Sys

A = Raw_input (' raw_input_name: ')

Print (a)

print ' Stdin_name: ', #逗号保持在同一行上

b = Sys.stdin.readline () [:-1] #-1 means drop line break \ n

Print (b)

(2.3) Redirect from console to file

Mport Sys

F_handler=open (' Out.log ', ' W ')

Sys.stdout=f_handler

print ' Hello '

The current file is reborn into a file Out.log, the file content is Hello


(3) capture Sys.exit (n) Call

Function: Executes to the end of the main program, the interpreter automatically exits, but if you need to exit the program halfway, you can call the Sys.exit function, with an optional integer parameter returned to the program that called it, indicating that you can capture the call to Sys.exit in the main program. (0 is normal exit, others are abnormal)

Def exitfunc ():

print "Hello World"

Sys.exitfunc = exitfunc # Set the function called when capturing

Print "AAAAAAAA"

Sys.exit (1) # After exiting the auto call Exitfunc (), the program still exits

print "There" # will not be print

Results:

Aaaaaaaa

Hello World

Explain:

1, set the Sys.exitfunc function, and when executing sys.exit (1), call the Exitfunc function

2,sys.exit (1) The contents will not be executed because the program has exited.


This article is from the "Note space" blog, so be sure to keep this source http://286577399.blog.51cto.com/10467610/1980801

2. Python Module

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.