Use of the Sys module in the Python Standard Library

Source: Internet
Author: User
Tags builtin exit in
This article describes how to use the Sys module in the Python standard library, this article describes how to use the sys module to obtain script parameters, processing modules, using the sys module to operate on module search paths, using the sys module to find built-in modules, and using the sys module to find imported modules., the sys module provides many functions and variables to process different parts of the Python runtime environment.

Process command line parameters

After the interpreter is started, the argv list contains all the parameters passed to the script. The first element in the list is the script name.

Use the sys module to obtain the script parameters

The code is as follows:


Print "script name is", sys. argv [0] # use sys. argv [0] to collect the script name

If len (sys. argv)> 1:
Print "there are", len (sys. argv)-1, "arguments:" # Use len (sys. argv)-1 number of collection parameters-1 minus [0] script name
For arg in sys. argv [1:]: # output all parameters except [0]
Print arg
Else:
Print "there are no arguments! "


If a script is read from a standard input (such as "python <sys-argv-example-1.py"), the script name is set to a null string.

If the script is passed as a string to python (using the-c option), the script name is set to "-c ".

Processing Module

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

When Python is started, the list is initialized based on built-in rules, the content of the PYTHONPATH environment variable, and the registry (Windows system.

Because it is just a normal list, you can operate it in the program,

Search for paths using the sys module operation module

The code is as follows:


Print "path has", len (sys. path), "members"

Sys. path. insert (0, "samples") # insert the path to path, [0]
Import sample

Sys. path = [] # Delete all paths in the path
Import random

Use sys module to find built-in modules

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

The code is as follows:


Def dump (module ):
Print module, "=> ",
If module in sys. builtin_module_names: # check whether the built-in module exists.
Print" "
Else:
Module = _ import _ (module) # path of the output module of a non-built-in module
Print module. _ file __

Dump ("OS ")
Dump ("sys ")
Dump ("string ")
Dump ("strop ")
Dump ("zlib ")

OS => C: \ python \ lib \ OS. pyc
Sys =>
String => C: \ python \ lib \ string. pyc
Strop =>
Zlib => C: \ python \ zlib. pyd

Use the sys module to find the imported modules

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

Python has imported many modules before processing your script.

The code is as follows:


Print sys. modules. keys ()


['OS. path',' OS ', 'exception',' _ main _ ', 'ntpath', 'strop', 'nt ',
'Sys ',' _ builtin _ ', 'Site', 'Signal', 'userdict ', 'string', 'Stat']

Use the sys module to obtain the current platform

Sys. platform: return to the current platform, for example, "win32" "linux2 ".

Process standard output/input

Standard input and standard errors (usually abbreviated as stdout and stderr) are pipelines built in every UNIX system.

When you print something, the result goes to the stdout pipeline;

When your program crashes and prints debugging information (such as traceback 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 in
>>> For I in range (3 ):
... Sys. stderr. write ('Dive In ')

Dive inDive in

Stdout is a file-like object. calling its write function can print any given string.

In fact, this is what the print function actually does. It adds a hard carriage return to the string you print and calls the sys. stdout. write function.

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

Like stdout, stderr does not add a hard carriage return for you.

Both stdout and stderr are class file objects, but they are only written.

They all have no read method, but only the write method. However, they are still class file objects, so you can assign them any other (class) file objects to redirect their output.

Use sys to redirect the output

The code is as follows:


Print 'Dive In' # standard output
Saveout = sys. stdout # save stdout before redirection. in this way, you can set it back to normal.
Fsock = open ('out. log', 'w') # open 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 just opened.

Print 'This message will be logged instead of displayed' # This will only print the output result to the log file; no output is displayed on the screen.

Sys. stdout = saveout # before we mess up stdout, let's set it back to the original method.

Fsock. close () # close the log file.

Redirection error message

Fsock = open ('error. log', 'w') # open the log file where you want to store debugging information.
Sys. stderr = fsock # assign the file object of the newly opened log file to stderr for a standard redirect error.
Raise Exception, 'This error will be logged' # raises an Exception. nothing is printed on the screen. all normal trace information has been written into error. log.

Note that you neither explicitly close the log file nor set stderr back to the initial value.

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

Print to stderr

Writing error messages to standard errors is very common, so there is a fast syntax to export the information immediately

The code is as follows:


>>> Print 'entering function'
Entering function
>>> Import sys
>>> Print> sys. stderr, 'entering function'

Entering function


The shortcut syntax of the print statement can be used to write any open files (or class file objects ).

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

Exit the program using the sys module

The code is as follows:


Import sys
Sys. exit (1)

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

Capture sys. exit call

The code is as follows:


Import sys
Print "hello"
Try:
Sys. exit (1)
Failed T SystemExit: # capture exit exceptions
Pass # no action after capture
Print "there"


Hello
There

If you want to clear some items (such as deleting temporary files) before exiting, you can configure an "exit handler", which will be automatically called when the program exits.

Another method for capturing sys. exit calls

The code is as follows:


Def exitfunc ():
Print "world"

Sys. exitfunc = exitfunc # set the function called during capture

Print "hello"
Sys. exit (1) # exit after the automatic call of exitfunc (), the program still exits
Print "there" # Not 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.