Python's logging module, OS module, commands module and SYS module

Source: Internet
Author: User
Tags exit in stdin python script

One, logging module

Import logginglogging.debug ('This isdebug message') logging.info (' This is info message ' ) logging.warning ('This waswarning message' is Warning message

By default, logging prints the log to the screen with a log level of warning;
Log level size relationships are: 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. Low disk space "). This 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

Typically, the log is written to a file with the following example:

ImportLogginglogging.basicconfig ( level=__debug__, format='% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s', datefmt='%y/%m/%d%h:%m:%s', filename='Momo.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:

  

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__.

Second, OS module

OS.GETCWD () Gets the current working directory, which is the directory path of the current Python script work
Os.chdir ("dirname") changes the current script working directory, equivalent to the shell CD
Os.curdir returns the current directory: ('. ')

Os.makedirs (' dirname1/dirname2 ') can generate multi-level recursive directories

Os.removedirs (' dirname1 ') if the directory is empty, then delete, and recursively to the previous level of the directory, if also empty, then delete, and so on
  Os.mkdir (' dirname ') generates a single-level directory, equivalent to mkdir dirname in the shell
  Os.rmdir (' dirname ') delete the single-level empty directory, if the directory is not empty can not be deleted, error, equivalent to the shell rmdir dirname
  Os.listdir (' dirname ') lists all files and subdirectories in the specified directory, including hidden files, and prints as a list
  Os.remove () Delete a file
  Os.rename ("Oldname", "newname") renaming files/directories
  Os.stat (' path/filename ') get File/directory information
  Os.symlink (' Path/filename ', ' ln_filename ') create symbolic links, source required absolute path
  Os.utime () Modify Time Properties

1. Get system type via OS

Import OS Print (Os.name)

Results:linux system Os.name is the os.name of the Posix,windows system is NT

2. Execute system commands

Context = Os.popen ('ipconfig'). Read ()print (context.find (' 192.168.56.1 '))

Results: 328

3. operation of files and directories

Print(Os.listdir ('.'))Print(OS.GETCWD ())Print(Os.listdir (OS.GETCWD ())) Os.chdir (R'F:\momo')Print(OS.GETCWD ()) Os.mkdir ('Test') Os.remove ('Momo.log')Print(OS.LINESEP)if  notOs.path.exists ('Test'): Os.mkdir ('Test')Else:    Print('test is ok!') A= Os.path.join ('.','AAA','BBB','CCC')Print(a)Print(Os.path.dirname (R'F:\test\test.py'))

  

Three, commands module

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

1.commands.getoutput (CMD)

Returns only the result of executing the shell command:

As an example:

[email protected] ~]# cat a.py

#!/usr/bin/env python

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

Import commands

cmd = ' ls/home/admin '

A = Commands.getoutput (cmd)

Print (Type (a))

Print (a)

Results:

[email protected] ~]# python a.py

<type ' str ' >

Nginx.conf

Nginx_upstream_check_module-master.zip

test.py

Commands is a module that provides support for the use of Shell commands in a Linux system environment, where many of our scripts and environments are running on Linux systems,

2. Commands.getstatusoutput (CMD)

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

[email protected] ~]# cat c.py

#!/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:

[email protected] ~]# python c.py

<type ' tuple ' >

0

Nginx.conf

Nginx_upstream_check_module-master.zip

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, is the execution result of our shell command, Python is a clever place for Python to copy to status and output in one by one ways.

Four, sys module

The SYS module provides a series of variables and functions for the Python runtime environment.

1.SYS.ARGV: You can use SYS.ARGV to get the list of parameters for the command line arguments that are currently executing.

 import   sys  if  __name__  = =  "  __main__   " :  print  ("  sys.argv[0] = {0}  Span style= "COLOR: #800000" > " .format (Sys.argv[0]))  print  ("  sys.argv[1] = {0}  Span style= "COLOR: #800000" > ". Format (sys.argv[1 print  ("  sys.argv[2] = {0}  Span style= "COLOR: #800000" > ". Format (sys.argv[2]) 

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 by redirecting output and input to other devices or handling them in a non-standard way. Examples are as follows:

ImportSYSif __name__=='__main__':    Print('####################') Sys.stdout.write ('Hello Huangdongju')    Print('Hello World') name= Raw_input ('Please input your name:')    Print('Hello'+name) address=Sys.stdin.readline ()Print(address) F= Open ('1.log','W') Sys.stdout=FPrint('aaaaaaaaa')    Print('Hello World')

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 exceptions). Examples are as follows:

ImportSYSdefHello ():Print('Hello')if __name__=='__main__': Sys.exitfunc=HelloPrint('Start') Sys.exit (1)    Print('End')

Python's logging module, OS module, commands module and SYS module

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.