Logging
Logging module
Let's look at an example.
Import logginglogging.debug ("This isdebug message") logging.info ( "This isinfo message") logging.warning ("Theiswarning message ")
Operation Result:
WARNING:root:this is WARNING message
Note: Three sentences are written in the program, but only one warning level log is printed on the screen
By default, logging tells the log to print to the screen, and the log level size relationship is: critical>error>warning>info>debug>notset
DEBUG: Detailed information, usually appearing only on diagnostic issues
INFO: Make sure everything works as expected
WARNING: Warning, there may be some unexpected things going on, but the software will work as expected
ERROR: A more serious problem, the software does not perform some functions
CRITICAL: A serious error, the program may not continue to run
Logging the default log level is info.
ImportLogginglogging.basicconfig ( level=__debug__, Format='% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s', Datefmt='%y/%m/%d%h:%m:%s', #datefmt= '%a,%d%b%Y%h:%m:%s ',Filename='Myapp.log', FileMode='W') Logger= Logging.getlogger (__name__) Logger.debug ("This is debug message") Logger.info ("This is info message") logger.warning ("This is warning message")
Operation Result:
Myapp.log is Debug Message is Info Message is warning message
OS Module
Use of the OS module
This module is used for invoking system commands through the OS module, obtaining the path, obtaining the type of the operating system, and so on.
1. Get system type via OS
Import OS
Print (Os.name)
If the Windows System os.name= ' NT ',
If it is a Linux system os.name= ' POSIX '.
2. Execute system command
Most of the time we use the Python Proxy system command
Import OS
Os.system (' ipconfig ')
Content = Os.popen (' ipconfig '). Read ()
Print (content)
Note:
Os.system (' ipconfig ') command calls system commands
Os.popen () Returns a file object that obtains the results of the last system command execution through File.read ()
3. Directory and file operations
ImportOSPrint(OS.GETCWD ())#Get PathOs.chdir ("D:")Print(OS.GETCWD ()) Os.chdir (R'E:\CNTV')#Switch DirectoriesPrint(Os.listdir (OS.GETCWD ()))#list files for the current directoryPrint(Os.listdir ('C:\Python27'))#list files for the specified directoryPrint(OS.GETCWD ())#os.mkdir ("text")Print(OS.LINESEP)#Print the operating system delimiter, Linux is \n,win is \ r \ nif notOs.path.exists ("Test"): Os.makedirs ("Test")Else: Print("Test US exists") A= Os.path.join ('.',"a","b","C")Print(a)#just stitching the current directoryPrint(Os.path.dirname (OS.GETCWD ()))
Print(Os.path.dirname (OS.GETCWD ()))#get a directory of filesNote:1, OS.GETCWD () Gets the current system program of the directory working hard2, os. ChDir (' target directory ') switch to target directory3, Os.listdir (' string directory ') lists all files in the string directory4,os.mkdir ('Catalogue') to create a directory5,os.remove ('1.txt'Delete file, error when file is not present6, OS.LINESEP print operating system delimiter, Linux system delimiter \n,windows system delimiter \r\n,mac system delimiter \ r7,os.path.join (OS.GETCWD (),'AAA', ' BBB ', ' CCC ') stitching out multilevel catalogs: E:\TEST\AAA\BBB\CCC8, os.path.exists (' directory ') to determine if the directory exists9, Os.path.split (' File or directory ') separates the last directory or file from the previous directory and returns a tuple10, Os.path.splitext (' file ') separates the file suffix name from the front and returns a Tupleos.fork ()
Commands module
The commands module only uses Linux and Shell mode
We often call system scripts or system commands to solve many problems, there are three ways to invoke system commands via Python: cmd for system command
A, commands.getoutput (CMD)
Returns only the result of executing the shell command
The return value of Commands.getoutput only returns the result
Import commands
cmd = "ls/home/"
result = Commands.getoutput (cmd)
Print (type (result))
Print (Result)
The return value of Commands.getstatusoutput is a tuple type
The first value accepts the status code, and the returned result is an int type
The second value accepts the return result, and the returned result is a str type
Import commands
cmd = "Ps-ef"
Status,result = commands.getstatusoutput (cmd)
Print (Type status)
Print (status)
Print (type (result))
Print (Result)
SYS module
1. Get program parameters through SYS module
Import Sys
if __name__ = = "__main__":
Print ("sys.argv[0]={0}". Format (Sys.argv[0]))
Print ("Sys.argv[1]={1}". Format (Sys.argv[1]))
2, Sys.stdout\stdin\stderr
The Stdout,stdin and stderr variables contain the stream object corresponding to the I/O stream
3. Sys.stdout and Print
When we call print obj in Python, we actually call Sys.stdout.write (obj + "\ n"), print the required content to the console, and then append a newline character. Print calls Sys.stdout's Write method
The following two lines are equivalent
Import Sys
Sys.stdout.write ("Hello" + "\ n")
Print ("Hello")
4. Redirect from console to file
Import Sys
T_handle = open (' Out.log ', ' W ')
Sys.stdout = T_handle
(iv) 4-5 Python's logging, OS, and SYS