[Reprint]python in the SYS module (ii)

Source: Internet
Author: User
Tags first string throw exception

 #  !/usr/bin/python  #   Filename:using_sys.py  import   sys  print    the command line arguments is:    for  i  SYS.ARGV:  print   i  print   " \n\nthe PYTHONPATH is  Span style= "color: #800000;" > ' , Sys.path,  " \n   '  

The output is as follows

How it works

First, we use the import statement to enter the SYS module . Basically, this statement tells Python that we want to use this module. The SYS module contains functions related to the Python interpreter and its environment.

When Python executes the import SYS statement, it looks for the sys.py module in the directory listed in the Sys.path variable. If this file is found, the statement in the main block of the module will be run and the module will be able to be used by you. Note that the initialization process only takes place the first time we enter the module. In addition, "SYS" is the abbreviation for "system".

The argv variable in the SYS module is indicated by the use of a dot--sys.argv--One advantage of this approach is that the name does not conflict with any argv variables that are used in your program. In addition, it clearly shows that this name is part of the SYS module.

The SYS.ARGV variable is a list of strings. In particular, SYS.ARGV contains a list of command-line arguments , which are parameters that are passed to your program using the command line.

If you use the IDE to write these programs, look for a way to specify the command-line arguments of the program in the menu.

Here, when we execute the Python using_sys.py we are arguments, we use the Python command to run the using_sys.py module, and the following content is passed as a parameter to the program. Python stores it in the SYS.ARGV variable for us.

Remember that the name of the script always sys.argv the first parameter of the list. So, here, ' using_sys.py ' is sys.argv[0], ' we ' are sys.argv[1], ' is ' is sys.argv[2] and ' arguments ' is sys.argv[3]. Note that Python starts counting from 0, not starting with 1.

The Sys.path contains the list of directory names for the input modules. We can observe that the first string of Sys.path is empty-this empty string indicates that the current directory is also part of the Sys.path, which is the same as the PYTHONPATH environment variable. This means that you can enter the module directly in the current directory. Otherwise, you have to put your module in one of the directories listed in Sys.path.

  from http://wiki.jikexueyuan.com/project/simple-python-course/example-eight-one.html ----------------- -------------This is the number of split-line----------------------------------------------------------------------------------------SYS module functions , I can only choose some of the functions I think are more useful here. SYS module is a lot of function, but we should focus on those functions is the most suitable for us, for this, I listed these functions, I think the more suitable for me to develop later functions. (1) sys.argv A lot of people would think, how can I pass parameters to my program externally? This, it can be achieved. such as: Tesy.pyimport Sysprint Sys.argv[number] In general, number 0 is the name of this script, ... The arguments passed under the command line. such as: test.py script content: Import sys print sys.argv[0]print sys.argv[1]print sys.argv[2]print sys.argv[3] then [[ email protected] scripts]# python test.py arg1 arg2 arg3test.pyarg1arg2arg3 See, the corresponding relationship? Also, in the Python.org module reference manual says, if the command line is selected under the C-argv[0]=-c  look, [[email protected] scripts]# python-c "Import sys;print Sys.argv[0];p rint sys.argv[1] "arg1-carg1 If you do not understand, you can refer to the man pythonsynopsis        python [-d] [-e] [-h] [-i] [-M module-name] [-O]         &N bsp;   &nbsp [-Q argument] [-S] [-T] [-U]              [-v] [-v] [-w argument] [ -X]              [-C command | script |-] [ Arguments] (2) Sys.platform We all know that today's programs are more popular across platforms. Simply said that this program can be in Windows, switch to Linux or can not be modified to run up, sounds good. So, this function can be useful. Suppose we want to implement a clearing terminal, Linux under Clear, Windows with Clsostype=sys.platform () If ostype== "Linux" or ostype== "linux2": cmd= "Clear" Else:  cmd= "CLS" (3)  sys.exit (n) executes to the end of the main program, the interpreter automatically exits .  but if you need to exit the program halfway,  you can call sys.exit  The function,  it with an optional integer parameter returned to the program that called it .  this means that you can capture a call to sys.exit  in the main program. (Note: 0 is normal exit, the other is not normal, can throw exception event for capture!) Import Sys def Exitfunc (value):     ' Clear function '     print value    sys.exit (0)  print "Hello"  try:     sys.exit (1) except Systemexit,value:    exitfunc (value)  print "COme? " Output: [[email protected] scripts]# python test.pyhello1 The following is the Python.org Library reference manual, excerpt from, for reference. Exit from Python. This was implemented by raising the systemexit exception, so cleanup actions specified by finally clauses of&nbsp ; Try statements is honored, and it's possible to intercept the exit attempt at a outer level. The optional argument arg can be a integer giving the exit status (defaulting to zero), or another type of obje Ct. If It is a integer, zero is considered "successful termination" and any nonzero value is considered "abnormal termination "By shells and the". Most systems require it to is in the range 0-127, and produce undefined results otherwise. Some Systems has a convention for assigning specific meanings to specific exit codes, but these is generally underdevelo Ped Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If Another type of object is passed, none is equivalent to passing Zero, and any other object was printed To sys.stderr and results in an exit code of 1. In Particular, sys.exit ("someError Message ")  is a quick way to exit a programs when an error occurs.  probably means that sys.exit exiting from a python program will produce a Systemexit exception , you can do some work to remove the rationale for this. The default normal exit status for this optional parameter is 0, and the value for the parameter range is: 0-127. Other values are non-normal exits, and another type, shown here is the strings object type. (4) Sys.path you have a certain understanding of the module? Do you need to import a function of the module before you use it? The answer is need. The import,__import__ command will not be carry work. So what happened to python inside when everyone was doing import module_name? To put it simply, search for module_name. Search for module.name>>> sys.path[', '/usr/local/lib/python24.zip ', '/usr/local/lib/python2.4 ', according to the path of Sys.path, '/ Usr/local/lib/python2.4/plat-freebsd4 ', '/usr/local/lib/python2.4/lib-tk ', '/usr/local/lib/python2.4/lib-dynload ', '/usr/local/lib/python2.4/site-packages '] everyone will be able to write the module can be placed on the above a certain directory, it can be correctly searched. Of course, you can also add your own module path. Sys.path.append ("Mine module Path") .  (5) Sys.modulesthis is a dictionary this maps module names to modules which has already been loaded. This can is manipulated to force reloading of modules and other tricks. The Python.org Handbook has already been said to be very clear. For names in Sys.modules.keys (): If names! = ' sys ':      (6) Sys.stdin,sys.stdout,sys.stderrstdin, stdout, and stderr variables contain stream objects that correspond to standard I/O streams. If you need more control over the output, and print does not meet your requirements, they are what you need. You can also replace them by redirecting output and input to other devices or by non-standard processing of articles they extract from the Web for your reference: #testing stdout

print ‘Hello World!‘
Running hello.py will print the Hello world! on the standard output screen, and we'll compile a simple standard input applet sayhi.py:
#testing stdin

print ‘Hi, %s!‘ % raw_input(‘Please enter your name:‘)
When you enter your name with the keyboard, the program outputs hi,[your name]! on the screen, which is the example from the standard input: keyboard to get information and then output to standard output: screen.
So how does print and raw_input relate to the standard input/output stream in the example above?
In fact, the Python program's standard input/output/error stream is defined in the SYS module, respectively: Sys.stdin, Sys.stdout, Sys.stderr
The above programs are the same as the following:
import sys

sys.stdout.write(‘Hello World!‘)
import sys

print ‘Please enter your name:‘,
name=sys.stdin.readline()[:-1]
print ‘Hi, %s!‘ % name

So Sys.stdin, Sys.stdout, stderr exactly what is it? We enter the following code in the Python Runtime environment:
import sys
for f in (sys.stdin, sys.stdout, sys.stderr): print f
输出为:
<open file ‘<stdin>‘, mode ‘r‘ at 892210>
<open file ‘<stdout>‘, mode ‘w‘ at 892270>
<open file ‘<stderr>‘, mode ‘w at 8922d0>

It can be seen that stdin, stdout, stderr in Python are nothing more than file attributes, they are automatically associated with the standard input, output, and error in the shell environment when Python starts.
The I/O redirection of the Python program in the shell is exactly the same as the DOS command at the beginning of this article, which is actually provided by the shell and is not related to python itself. So can we redirect Stdin,stdout,stderr Read and write operations to an internal object inside a python program? The answer is yes.
Python provides a Stringio module to complete this idea, such as:
From Stringio import Stringio
Import Sys
Buff =stringio ()

temp = sys.stdout #保存标准I/o Flow
Sys.stdout = Buff #将标准I/o flow redirect to Buff object
Print, ' hello ', 0.001

Sys.stdout =temp #恢复标准I/O Flow
Print Buff.getvalue () This article from "Bad Boy" blog, provenance http://5ydycm.blog.51cto.com/115934/304324

[Reprint]python in the SYS module (ii)

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.