The use of the Sys module of the Python standard library is detailed

Source: Internet
Author: User
Tags builtin exit in

The SYS module provides a number of functions and variables to handle different parts of the Python runtime 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.

Using the SYS module to get the parameters of the script

Copy CodeThe code is as follows:
Print "Script name is", Sys.argv[0] # Capture script name using sys.argv[0]

If Len (SYS.ARGV) > 1:
Print "There is", Len (SYS.ARGV)-1, "Arguments:" # Use Len (SYS.ARGV)-1 to collect the number of parameters-1 is minus [0] script name
For ARG in sys.argv[1:]: All parameters outside #输出除了 [0]
Print arg
Else
Print "There is no arguments!"


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

If you pass the script as a string to Python (using the-C option), the pin name is set to "-C".

Processing module

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

When you start Python, this list is initialized from the contents of the PYTHONPATH environment variable, as well as the registry (Windows system), based on the built-in rules.

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

Search paths using the SYS module action module

Copy CodeThe code is as follows:
Print "Path have", Len (Sys.path), "members"

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

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

Using the SYS module to find built-in modules

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

Copy CodeThe code is as follows:
def dump (module):
Print module, "= =",
If module in Sys.builtin_module_names: #查找内建模块是否存在
Print "<BUILTIN>"
Else
Module = _ _import_ _ (module) #非内建模块输出模块路径
Print Module._ _file_ _

Dump ("OS")
Dump ("SYS")
Dump ("string")
Dump ("Strop")
Dump ("zlib")

OS = C:\python\lib\os.pyc
SYS = <BUILTIN>
string = C:\python\lib\string.pyc
Strop = <BUILTIN>
Zlib = C:\python\zlib.pyd

Using the SYS module to find imported modules

The modules dictionary contains all the loaded modules. Import statements Check this dictionary before importing content from disk.

Python has imported many modules before processing your script.

Copy CodeThe code is as follows:
Print Sys.modules.keys ()


[' Os.path ', ' OS ', ' Exceptions ', ' _ _main_ _ ', ' Ntpath ', ' strop ', ' NT ',
' sys ', ' _ _builtin_ _ ', ' site ', ' signal ', ' userdict ', ' string ', ' stat ']

Using the SYS module to get the current platform

Sys.platform return to the current platform such 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 each UNIX system.

When you print something, the result goes 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

Copy CodeThe 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, and the write function that calls it can print out any string you have given.

In fact, this is what the print function really does; it adds a hard carriage 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;

Both stdout and stderr are class file objects, but they are all 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.

Using the SYS redirection output

Copy CodeThe code is as follows:
print ' Dive in ' # Standard output
Saveout = sys.stdout # will save stdout before redirection, so you can then 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 was just opened.

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

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

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 the Error.log

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

This is good, because once the program crashes (due to the exception thrown), Python will clean up 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

Copy CodeThe 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 class file object).

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

Using the Sys module to exit a program

Copy CodeThe 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

Copy CodeThe code is as follows:
Import Sys
print "Hello"
Try
Sys.exit (1)
Except Systemexit: # Catching an exit exception
Pass # No action after capture
print "There"


Hello
There

If you are ready to clean up some things yourself before exiting (such as deleting temporary files), you can configure a "exit handler" (exit handler), which will be automatically called when the program exits.

Another way to capture Sys.exit calls

Copy CodeThe code is as follows:
Def exitfunc ():
Print "World"

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

print "Hello"
Sys.exit (1) # After exiting the auto call Exitfunc (), the program still exits
print "There" # will not be print

Hello
World

The use of the Sys module of the Python standard library is detailed

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.