The Python standard library SYS module uses the detailed

Source: Internet
Author: User
Tags builtin exit in in python

This article mainly introduces the Python standard library of the SYS module, this article explains the use of the SYS module to obtain the parameters of the script, processing modules, using the SYS module to operate the module search path, using the SYS module to find the built-in modules, using the SYS module to find imported modules, and other use cases, Need friends can refer to the following

The SYS module provides many functions and variables to handle different parts of the Python run-time environment.

Handling Command Line Arguments

After the interpreter starts, the argv list contains all the parameters passed to the script, and the first element of the list is the name of the script itself.

Use the SYS module to get the parameters of the script

The code is as follows:

Print "Script name is", Sys.argv[0] # using sys.argv[0] to capture script names

If Len (SYS.ARGV) > 1:

Print "There are", Len (SYS.ARGV)-1, "Arguments:" # Use Len (SYS.ARGV)-1 to capture the number of parameters-1 for minus [0] script name

For ARG in sys.argv[1:]: #输出除了 [0] all parameters outside

Print arg

Else

Print "There are no arguments!"

If you read from a standard input script (such as "Python < sys-argv-example-1.py"), the script's name will be set to an empty string.

If the script is passed as a string to Python (using the-C option), the name of the foot is set to "-C".

Processing module

The path list is a list of directory names from which Python looks for extension modules (Python source module, compilation module, or binary extension).

When you start Python, the list is initialized from the built-in rules, the contents of the Pythonpath environment variables, and the registry (Windows system).

Because it's just a normal list, you can manipulate it in a program,

Manipulating module search paths using the SYS module

The code is as follows:

Print "Path has", Len (Sys.path), "members"

Sys.path.insert (0, "samples") #将路径插入到path, [0]

Import sample

Sys.path = [] #删除path中所有路径

Import Random

Use the SYS module to find the built-in modules

The Builtin_module_names list contains the names of all the built-in modules in the Python interpreter

The code is as follows:

def dump (module):

Print module, "=>",

If module in Sys.builtin_module_names: #查找内建模块是否存在

Print " "

Else

Module = _ _import_ _ (module) #非内建模块输出模块路径

Print Module._ _file_ _

Dump ("OS")

Dump ("SYS")

Dump ("string")

Dump ("Strop")

Dump ("zlib")

OS => C:PYTHONLIBOS.PYC

SYS =>

String => C:PYTHONLIBSTRING.PYC

Strop =>

Zlib => C:pythonzlib.pyd

Use the SYS module to find imported modules

The modules dictionary contains all the loaded modules. The import statement checks the dictionary before importing content from disk.

Python has already imported a lot of modules before processing your script.

The code is as follows:

Print Sys.modules.keys ()

[' Os.path ', ' OS ', ' Exceptions ', ' _ _main_ _ ', ' Ntpath ', ' strop ', ' NT ',

' sys ', ' _ _builtin_ _ ', ' site ', ' signal ', ' userdict ', ' string ', ' stat '

Use the SYS module to get the current platform

Sys.platform return to the current platform appears as: "Win32" "LINUX2" and so on

Process standard output/input

Standard input and standard errors (usually abbreviated as STDOUT and STDERR) are pipelines built into every UNIX system.

When you print something, the results go to the STDOUT pipeline;

When your program crashes and prints out debugging information (such as Traceback (Error tracking) in Python), the information goes to the STDERR pipeline

The code is as follows:

>>> for I in range (3):

... print ' Dive in '

Dive in

Dive in

Dive in

>>> Import Sys

>>> for I in range (3):

... sys.stdout.write (' Dive in ')

Dive indive indive in

>>> for I in range (3):

... sys.stderr.write (' Dive in ')

Dive indive indive in

StdOut is a class file object; The Write function that calls it can print out any string you give.

In fact, that's what the print function really does; it adds a hard return after the string you print, and then calls the Sys.stdout.write function.

In the simplest case, stdout and stderr send their output to the same place.

Like stdout, stderr does not add hard returns for you, and if necessary, add it yourself.

Both stdout and stderr are class file objects, but they are both write-only.

None of them have the Read method, only the Write method. However, they are still class file objects, so you can assign any other (class) file objects to them to redirect their output.

Redirecting output with Sys

The code is as follows:

print ' Dive in ' # Standard output

Saveout = Sys.stdout Save stdout before redirection, so you can set it back to normal

Fsock = open (' Out.log ', ' W ') # Opens a new file for writing. If the file does not exist, it will be created. If the file exists, it will be overwritten.

Sys.stdout = fsock # All subsequent output will be redirected to the new file that you just opened.

print ' This would be logged instead of displayed ' # so that the output will only be "printed" to the log file; the output will not be visible on the screen

Sys.stdout = saveout # before we mess up the stdout, let's set it back to the way it used to be.

Fsock.close () # Closes the log file.

REDIRECT Error message

Fsock = open (' Error.log ', ' W ') # Opens the log file where you want to store debug information.

Sys.stderr = fsock # Assigns the file object of the newly opened log file to stderr to redirect the standard error.

Raise Exception, ' This error would be logged ' # throws an exception, does not print anything on the screen, all normal trace information has been written into Error.log

Also note that you have neither explicitly closed the log file nor set stderr back to the original value.

This is good, because once the program crashes (due to the exception thrown), Python will clean and close the file for us

Print to stderr

It is common to write error messages to standard errors, so there is a faster syntax to export information immediately

The code is as follows:

>>> print ' entering function '

Entering function

>>> Import Sys

>>> print >> sys.stderr, ' entering function '

Entering function

The shortcut syntax for the PRINT statement can be used to write to any open file (or a class file object).

Here, you can redirect a single print statement to stderr without affecting the subsequent print statement.

To exit a program using the SYS module

The code is as follows:

Import Sys

Sys.exit (1)

Note that Sys.exit does not exit immediately. Instead, a Systemexit exception is thrown. This means that you can capture calls to Sys.exit in the main program.

Capturing Sys.exit Calls

The code is as follows:

Import Sys

print "Hello"

Try

Sys.exit (1)

Except Systemexit: # Capture Exit exception

Pass # Capture without any action

print "There"

Hello

There

If you're ready to clean up something (such as deleting a temporary file) before exiting, you can configure an "exit handler" (exit handler) that will automatically be invoked when the program exits.

Another way to capture Sys.exit calls

Copy code code as follows:

Def exitfunc ():

Print "World"

Sys.exitfunc = Exitfunc # Set functions that are called when caught

print "Hello"

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

print "There" # will not be print

Hello

World

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.