python--Standard library SYS module

Source: Internet
Author: User
Tags 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

------------------------------------------------------------------------------------------------------
Print "Script name is", Sys.argv[0] # Capture script name using sys.argv[0]

If Len (SYS.ARGV) > 1:
Print "Thereare", Len (SYS.ARGV)-1, "arguments:" #使用len (SYS.ARGV)-1 Number of acquisition parameters-1 minus [0] script name
For ARG insys.argv[1:]: all parameters outside #输出除了 [0]
Print arg
Else
Print "Thereare 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

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

------------------------------------------------------------------------- -----------------------------
Def dump (module):
    printmodule, "= =",
     if module insys.builtin_module_names:   #查找内建模块是否存在
        print ""
    else:
       module = _ _ import__ (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

------------------------------- -----------------------------------------------------------------------

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.

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

------------------------------------------------------------------------------------------------------
>>> for I in range (3):
...      print ' Divein '

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 (' Divein ')

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

------------------------------------------------------------------------------------------------------

print ' Divein ' #标准输出
Saveout =sys.stdout # Save stdoutbefore 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 you just opened.

print ' thismessage will is logged instead ofdisplayed ' #这样只会将输出结果 "printing" to the log file; the output is not visible on the screen

Sys.stdout =saveout #在我们将stdout mess up before let's set it back to the original way.

Fsock.close () #关闭日志文件.

------------------------------------------------------------------------------------------------------

REDIRECT Error message

------------------------------------------------------------------------------------------------------

Fsock = open (' Error.log ', ' W ') #打开你要存储调试信息的日志文件.
Sys.stderr =fsock #将新打开的日志文件的文件对象赋值给stderr to redirect the standard error.
RaiseException, ' This error would belogged ' #引发一个异常, no 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 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

------------------------------------------------------------------------------------------------------

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

Enteringfunction

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

------------------------------------------------------------------------------------------------------

Import Sys
Sys.exit (1)

Note 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

------------------------------------------------------------------------------------------------------

Import Sys
print "Hello"
Try
Sys.exit (1)
Exceptsystemexit: # catching an exit exception
Pass #捕获后不做任何操作
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

------------------------------------------------------------------------------------------------------
Def exitfunc ():
Print "World"

Sys.exitfunc =exitfunc #设置捕获时调用的函数

print "Hello"
Sys.exit (1) after #退出自动调用exitfunc (), the program still quits
Print "There" # will not be print

Hello
World

------------------------------------------------------------------------------------------------------

python--Standard library 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.