First, the definition
The SYS module provides a number of functions and variables to handle different parts of the Python runtime environment.
Second, commonly used functions
1 sys.argv command line argument list, the first element is the program itself path 2 sys.exit (n) exit the program, exit normally exits (0)3 sys.version Get version information for Python interpreter 4 sys.maxint Maximum int value 5 sys.path returns the search path of the module, using the value of PYTHONPATH environment variable when initializing 6 Sys.platform returns the operating system platform name
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
1 Print "Script Name is", Sys.argv[0]#use sys.argv[0] to capture script names2 ifLen (SYS.ARGV) > 1:3 Print "there is", Len (SYS.ARGV)-1,"arguments:" #use Len (SYS.ARGV)-1 to collect the number of parameters-1 for minus [0] script name4 forArginchSys.argv[1:]:#output all parameters except [0]5 PrintArg6 Else:7 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
1 print " path has ", Len (sys.path), " members " 2 sys.path.insert (0, " samples " ) # insert path into path,[0] 3 import sample 4 sys.path = [] # delete all paths in path 5 Span style= "COLOR: #0000ff" >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
1 defDump (module):2 PrintModule"=",3 ifModuleinchSys.builtin_module_names:#Find out if the built-in module exists4 Print "<BUILTIN>"5 Else:6Module = _ _import_ _ (module)#non-built-in module output module path7 PrintModule._ _file_ _8Dump"OS")9Dump"SYS")TenDump"string") OneDump"strop") ADump"zlib") -OS =C:\python\lib\os.pyc -SYS = <BUILTIN> theString =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.
PrintSys.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
1>>> forIinchRange (3):2...Print'Dive in'3 4 5Diveinch6Diveinch7Diveinch8>>>ImportSYS9>>> forIinchRange (3):Ten... sys.stdout.write ('Dive in') One ADive indive indiveinch ->>> forIinchRange (3): -... sys.stderr.write ('Dive in') the -Dive indive indiveinch
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 'Dive in' #Standard OutputSaveout = Sys.stdout#save stdout before redirection, so you can then set it back to normalFsock = 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' #This will only "print" the output to the log file, and 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 original way. fsock.close ()#close 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
Print ' entering function ' entering function Import SYS Print ' 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
Import Syssys.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
1 ImportSYS2 Print "Hello"3 Try:4Sys.exit (1)5 exceptSystemexit:#catching an exit exception6 Pass #no action after capture7 Print "there"8 9 Ten One Hello AThere
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
1 defExitfunc ():2 Print " World"3 4 5Sys.exitfunc = Exitfunc#to set the function called when capturing6 7 Print "Hello"8Sys.exit (1)#after exiting the automatic call to Exitfunc (), the program still exits9 Print "there" #will not be printTen One Hello AWorld
Iii. Examples of progress bars
1 defProgress (PERCENT,WIDTH=50):#Wuyi2 ifPercent >= 100:3 #print (' \r[%s] 100%% '% (width* ' # '))4percent=1005Show_str= ('[%%-%ds]'%width)% (int (width*percent/100) *'#')6 Print('\r%s%d%%'% (show_str,percent), file=sys.stdout,flush=true,end="')7 #8total_size=10251219Recv_size=0Ten One whileRecv_size <total_size: ATime.sleep (0.01)#Network latency for simulated downloads -recv_size+=1024 -Recv_per=int (100*recv_size/total_size) theProgress (RECV_PER,WIDTH=10)
Python SYS Module