Dave Python exercise sixteen-execution environment

Source: Internet
Author: User
Tags builtin

# Encoding = UTF-8 <br/> ************ * ******** </P> <p >## ************** Part 1: * <br/> # Many Python objects are called, that is, any object that can be called through the function operator. <Br/> # To Call callable objects, function operators must follow the callable objects. For example, use "Foo ()" to call the function "foo ". <Br/> # callable objects can be called through functional programming interfaces, such as apply (), filter (), map (). <Br/> # Python has four types of callable objects: functions, methods, classes, and instances of some classes. Remember that any reference or alias of these objects is callable. </P> <p >#### 1.1 functions <br/> # Python has three function objects of different types. </P> <p >## 1.1.1 built-in function (BIFS) <br/> # BIF is written in C/C ++ and compiled into the python interpreter, then they are loaded into the system as part of <br/> # Of the First (built-in) namespace. These functions are in the _ bulitin _ module and imported to the interpreter as the _ builtins _ module. </P> <p> # built-in Function Attributes <br/> # BIF attribute description <br/> # BIF. _ Doc _ document string (or none) <br/> # BIF. _ name _ document name of the string type <br/> # BIF. _ self _ set to none (reserved for the built-in method) <br/> # BIF. _ module _ stores the module name defined by BIF (or none) </P> <p> # You can use Dir () to list all the attributes of a function: <br/> # print (Dir (type) <br/> # ['_ abstractmethods _', '_ base __', '_ bases _', '_ basicsize _', '_ call _', '_ class __', <br/> # '_ delattr _', '_ dict _', '_ dictoffset _', '_ Doc __', '_ eq _', '_ fla GS _ ',' _ format _ ', <br/> #' _ Ge _ ',' _ getattribute __', '_ GT _', '_ Hash _', '_ init _', '_ instancecheck _', '_ itemsize __', <br/> # '_ Le _', '_ LT _', '_ module _', '_ Mro __', '_ name _', '_ ne _', '_ new _', '_ prepare __', <br/> # '_ reduce _', '_ performance_ex _', '_ repr _', '_ setattr __', '_ sizeof _', '_ STR _', '_ subclasscheck _', <br/> # '_ subclasses __', '_ subclasshook _', '_ weakrefoffset __', 'Mro'] </P> <p> # according to the internal mechanism, because BIFS and built-in methods (BIMs) belong to the same type, type () is called for BIF or bim () the result is: <br/>#>> type (DIR) <br/> # <type 'builtin _ function_or_method '> </P> <p> # note that this cannot be applied to factory functions, because type () returns the type of the generated object: <br/>#>> type (INT) <br/> # <type 'type'> <br/>#>> type (type) <br/> # <type 'type'> </P> <p> #1.1.2 User-Defined Function (UDF) <br/> # UDF (User-Defined Function, user-Defined Functions are usually written in Python and are defined at the highest level in the module. <br/> # therefore, they are used as part of the global namespace (once a built-in namespace is created) load to the system. The function can also be defined in another letter <br/> # Number body. Now, you can access attributes in multiple nested scopes. You can use the func_closure attribute to hook attributes defined elsewhere. </P> <p> # User-Defined Function Attributes <br/> # UDF attribute description <br/> # UDF. _ Doc _ document string (you can also use UDF. func_doc) <br/> # UDF. _ name _ string-type function name (you can also use UDF. func_name) <br/> # UDF. code object compiled by func_code byte <br/> # UDF. func_defaults default parameter tuples <br/> # UDF. func_globals global namespace dictionary; same as calling globals (x) from the function <br/> # UDF. namespace of the func_dict function attribute <br/> # UDF. func_doc (see the UDF above. _ Doc _) <br/> # UDF. func_name (see the UDF above. _ name _) <br/> # UDF. func_closure contains the reference unit object tuples of free variables </P> <p> # Internal Mechanism The user-defined function is of the "function" type. <br/> # The Lambda expression is slightly different from the User-Defined Function. Although they also return a function object, <br/> # Lambda expressions are not created using the def statement, but with the lambda Keyword: <br/> # Because lambda expressions do not provide the basic structure for the code bound to the name, they must be called through functional programming interfaces, <br/> # or assign their references to a variable, and then you can call them directly or call them through functions. The variable is only an alias. <br/> # It is not the name of the function object. <Br/> # the object for creating a function through Lambda has the same attributes as the User-Defined Function except that it has no name; __name __< br/> # or set the func_name attribute to the string "<Lambda> ". Use the type () factory function to demonstrate the lambda expression <br/> # return the same function object as the User-Defined Function. <Br/>#< br/>#>> lambdafunc = Lambda X: x * 2 <br/>#>> lambdafunc (100) <br/> #200 <br/> #> type (lambdafunc) <br/> # <type 'function'> </P> <p> #### 1.2 method <br/> # a user-defined method is part of a class.. Many Python data <br/> # types, such as lists and dictionaries, also have methods. These are called built-in methods. To further describe the type of "ownership", Party <br/> # naming is performed by the object name and period attribute identifier. </P> <p> # built-in method (BIM) attributes <br/> # Bim attribute description <br/> # Bim. _ Doc _ document string <br/> # Bim. _ name of a string function <br/> # Bim. _ self _ bound object </P> <p >## 1.2.1 built-in method (BIMs) <br/> # Both Bim and BIF share the same attributes. The difference is that the _ self _ attribute of Bim points to a python object, while BIF points to none. </P> <p> # Only the built-in type (BIT) has Bim. for the built-in method, the type () factory function provides the same output as bif. Note: How do we provide a built-in object to access bim: <br/>#>> type ([]. append) <br/> # <type 'builtin _ function_or_method '> </P> <p> # This object can be used as a parameter for classes and instances, use the built-in function Dir () to obtain their data and method attributes. This can also be used on Bim: <br/>#>> Dir ([]. append) <br/> # ['_ call _', '_ class _', '_ CMP _', '_ delattr __', '_ Doc _', <br/> # '_ getattribute _', '_ Hash _', '_ init __', '_ module _', <br/> # '_ name _', '_ new _', '_ reduce __', '_ performance_ex _', <br/> # '_ repr _', '_ self _', '_ setattr __', '_ STR _'] </P> <p >## 1.2.2 user-defined method (UDM) <br/> # UDM (user-defined method, methods defined by the user) are included in the class definition and only packaged with standard functions. <br/> # Only the classes that define them can be used. If they are not overwritten in the subclass definition, you can call them through the subclass instance. </P> <p> # The UDM is associated with the Class Object (non-binding method), but can only be called through the class instance (binding <br/> # method ). Regardless of whether udms is bound or not, all umds are of the same type-"instance method", </P> <p >#>> class C (object ): # define class # definition class <br/> #... def Foo (Self): pass # define UDM <br/> #... <br/>#>> C = C () # instantiation # instantiate <br/>#>> type (c) # type of class # category of the class <br/> # <type 'type'> <br/> #> type (c) # type of instance # instance type <br/> # <class '_ main __. c'> <br/>#>> type (C. foo) # type of unbound method # category of the non-binding method <br/> # <type 'instancemet Hod'> <br/>#>> type (C. foo) # type of bound method # type of the binding method <br/> # <type 'instancemethod'> </P> <p> # user-defined attributes <br/> # UDM attributes description <br/> # UDM. _ Doc _ document string (with UDM. im_fuc. _ Doc _ Same) <br/> # UDM. _ name _ string type method name (with UMD. im_func. _ name _ Same) <br/> # UDM. _ module _ define the udm Module name (or none) <br/> # UDM. the class associated with the im_class method (for the bound method; if it is not bound, it is the class that requires UDM) <br/> # UDM. function object of the im_func method (see udfs) <br/> # UDM. im_self is the associated instance if it is bound, and if it is not bound, it is none </P> <P >#### 1.3 class <br/> # You can use the class's callability to create an instance. The result of the "call" class is the creation of an instance, that is, the instance that everyone knows <br/>. Class has a default constructor, which does not do anything. Basically, there is only one pass statement. Programmers can customize the instantiation process by implementing the <br/>#__ int _ () method. Any parameters of the instantiated call will be passed into the constructor. </P> <p >#### 1.4 class instance <br/> # Python provides a special method named _ call _ to the class, this method allows programmers to create callable objects (instances ). <Br/> # in this case, the __call _ () method is not implemented, which means that most instances cannot be called. However, if this method is overwritten in the class <br/> # definition, the instance of this class becomes callable. Calling such an instance object is equivalent to calling the <br/> #__ call _ () method. any parameters provided in the instance call will be passed in _ call. </P> <p> # Then Foo () and foo. _ call _ (FOO) has the same effect. foo is also used as a parameter here because it is a reference to itself, the instance changes from <br/> # To the first parameter of each method call. If ___ call ___ () has parameters, such as (self, ARG), Foo (ARG) is the same as calling Foo. _ call _ (Foo, ARG. </P> <p> # class C (object): <br/> # def _ call _ (self, * ARGs ): <br/> # print ("I'm callable! Called with ARGs: \ n ", argS) </P> <p> # ************ Part 2: code object ***************** <br/> # callable objects are the most important part of the python execution environment, however, they are only the tip of the iceberg. Python statements, value assignment, <br/> # expressions, and even modules constitute a larger scene. These executable objects cannot be called as callable objects. More precisely <br/> #, these objects are only a small part of the puzzle that Forms executable code blocks, which are called code objects. </P> <p> # The core of each callable object is a code object consisting of statements, values, expressions, and other callable objects. View 1 <br/> # A module means to observe a large object that contains all the code in the module. Then the code can be divided into statements, values, tables <br/> # expressions, and callable objects. The callable object can be recursively decomposed to the next layer, where it has its own code object. </P> <p> # generally, code objects can be executed as part of a function or method call, or exec statements or built-in functions <br/> # eval (). As a whole, the Code object of a python module is all the code of this module. </P> <p> # To execute Python code, the code must first be converted to byte-compiled code (also known as bytecode ). This is <br/> # The real code object. However, they do not contain any information about their execution environment, which is why callable objects exist. <br/> # It is used to wrap a code object and provide additional information. </P> <p >## ************* Part 3: executable object declarations and built-in functions ******************* <br/> # Python provides a large number of BIF support for callability /executable object, these include exec statements. These function helper programs <br/> # workers can execute code objects, or use the built-in function complie () to generate code objects. </P> <p> # description of built-in functions and statements <br/> # callable (OBJ) returns true if OBJ can be called, otherwise, false is returned. <br/> # compile (string, file, type) creates a code object from the type. file is the place where the code is stored (usually set "") <br/> # eval (OBJ, Glo-BALS = globals (), locals = locals () Evaluate obj. obj is the expression compiled as a code object, or a string expression. It can provide a global or/or local namespace <br/> # exec OBJ executes a collection of OBJ, single Python statements, or statements, that is to say, the format is a code object or string; OBJ can also be a file object (which has been opened <br/> # In a valid Python script) <br/> # input (prompt = '') is equivalent to eval (raw_input (prompt =") </P> <P >### 3.1 callable () <br/> # callable () is a Boolean function that determines whether an object can be called through the function operator. If the function is callable, true is returned; otherwise, false is returned. <br/> # print (callable (DIR) <br/> # print (callable (1 )) <br/> # --> <br/> # True <br/> # False </P> <p> ### 3.2 compile () <br/> # The compile () function allows programmers to quickly generate code objects at runtime, and then they can use exec statements or built-in functions <br/> # eval () to execute these objects or evaluate them. An important point is that exec and eval () both can execute the Python code in the string format <br/>. When you execute code in the string format, you must compile the code in bytes each time. <Br/> # The compile () function provides one-time pre-Compilation of byte code, </P> <p> # The Three compile parameters are required. The first parameter represents the Python code to be compiled. The second string, although <br/> # is required, is usually set as an empty string. This parameter represents the name of the file that stores the code object (string type ). Compile <br/> # the common usage is to dynamically generate Python code in the form of strings, and then generate a code object-the code is obviously not stored in any file. <Br/>#< br/> # The final parameter is a string used to indicate the type of the Code object. There are three possible values: <br/> # 'eval' evaluable expressions [and eval () use Together] <br/> # 'singles' single executable statement [used together with exec] <br/> # 'exec 'executable statement group [used together with exec] </P> <p> # evaluable expression <br/> # eval_code = compile ('2014 + 1, 100 ', '', 'eval') <br/> # print (eval (eval_code )) <br/> # --> <br/> #300 </P> <p> # single executable statement <br/> # single_code = compile ('print ("Hello World! ") ','', 'Single') <br/> # print (single_code) <br/> # exec (single_code) <br/> # --> <br/> # <code object <module> at 0x0000000002275718, file "", line 1> <br/> # Hello world! </P> <p> # executable statement group <br/> # exec_code = compile ("" <br/> # Req = input ('count How many numbers? ') <Br/> # For eachnum in range (INT (req): <br/> # print (eachnum) <br/> #""",'', 'exec ') <br/> # exec (exec_code) <br/> # --> <br/> # count how many numbers? 4 <br/> #0 <br/> #1 <br/> #2 <br/> #3 </P> <p >## 3.3 eval () <br/> # eval () evaluates the expression, which can be a pre-compiled code object created by a string or built-in function complie. This is the first and most important parameter of <br/> # eval. The second and third parameters are optional and represent the objects in the global and local namespaces respectively. <Br/> # If the two parameters are given, globals must be a dictionary, and locals can be any ing object. For example, a _ getitem __() method object. <Br/> # if these two parameters are not provided, the default values are the objects returned by globals () and locals (). If only one global dictionary is input, the dictionary is also passed in as locals. </P> <p> # print (eval ('000000') <br/> #932 <br/> # print (INT ('000000 ')) <br/> #932 <br/> # in this case, both eval () and INT () return the same result: an integer of 932. However, they use different methods <br/>. The built-in function eval () receives a string in quotation marks and evaluates it as a python expression. The built-in function int () receives <br/> # represents an integer string and converts it to an integer. This is successful only when the string is only composed of a string of 932, and <br/> # the return value of the string as the expression 932,932 is also an integer represented by the string "932. When we use a pure string expression <br/> #, the two are no longer the same: <br/> # print (eval ('2017 + 123 ')) <br/> #300 <br/> # print (INT ('2014 + 100 ') <br/> # valueerror: Invalid literal for int (): 100 + 200 </P> <p> #3.4 exec </P> <p> # similar to eval (), exec statements run Python code in the form of code objects or strings. Similarly, using compile () <br/> # pre-compiled duplicate code helps improve performance because it does not need to be compiled in bytes during the call. The exec statement only accepts one parameter. <br/> # The following is its general syntax: <br/> # exec OBJ </P> <p> # the object to be executed (OBJ) can only be the original string, such as a single statement or statement group, they can also be pre-compiled into <br/> # A code object (using the 'singles' and 'exec "parameters respectively) </P> <p> # exec_code = compile ("<br/> # Req = input ('count How many numbers? ') <Br/> # For eachnum in range (INT (req): <br/> # print (eachnum) <br/> #""",'', 'exec ') <br/> # exec (exec_code) </P> <p >## 3.5 input () <br/> # the built-in function input () is eval () the combination of raw_input () is equivalent to eval (raw_input ()). Similar to <br/> # raw_input (), input () has an optional parameter, which represents a string prompt for the user. If no parameter <br/> # is specified, the string is an empty string by default. <Br/> # In terms of function, input is different from raw_input (), because raw_input () is always returned in the form of a string and uses the input of the <br/> # user. Input () performs the same task. In addition, it uses the input as a python expression to evaluate the value. This means that the data returned by <br/> # input () is the result of evaluating the input expression: a python object. </P> <p >## ************* Part 4: execute other commands (not Python) * <br/> # We can also execute non-Python programs in the python program. These programs include binary executable files and other <br/> # shell scripts. All requirements are only a valid execution environment. For example, to allow file access and execution, script files must be <br/> # interpreters that can access them (Perl, Bash, and so on ), the binary value must be accessible (compatible with the architecture of the Local Machine) </P> <p> # execute the OS module function of the external program (U is only valid for UNIX, W is only valid for Windows) <br/> # OS module function description <br/> # System (CMD) executes the program cmd (string) and waits until the program ends, return the exit code (always 0 in Windows) <br/> # fork () creates a child process in parallel with the parent process [usually used together with exec * ()]; returns two times .... one request to the parent process and one request to the child process <br/> # execl (file, arg0, arg1 ,...) execv (file, Arglist) is the same as execl () except for the parameter vector list. <br/> # Execle (file, arg0, arg1 ,... ENV) is the same as execl, but the environment variable dictionary env is provided <br/> # execve (file, Arglist, ENV) except for parameters with vector list, other and execle () same <br/> # execlp (CMD, arg0, arg1 ,...) the same as execl (), but the full file path name is searched in the user's search path <br/> # execvp (CMD, Arglist) in addition to the parameter vector list, And execlp () same <br/> # execlpe (CMD, arg0, arg1 ,... ENV) is the same as execlp, but the environment variable dictionary env <br/> # execvpe (CMD, Arglist, ENV) is the same as execvp, however, the environment variable dictionary env <br/> # spawn * a (mode, file, argS [, ENV]) spa is provided. Wn * () Family executes the path in a new process. ARGs is used as the parameter, and the dictionary of environment variables, ENV; Mode) yes <br/> # Magic tricks that display different operation modes. <Br/> # Wait () waits for the child process to complete [usually used together with Fock and exec * ()] ○ U <br/> # waitpid (PID, options) wait for the specified sub-process to complete [usually used together with Fock and exec * ()] ○ U <br/> # popen (CMD, mode = 'R', buffering =-1) run the CMD string to return a class file object as the communication handle of the running program. The default value is read mode and default system buffer. <br/> # startfileb (PATH) use the associated application execution path W </P> <p >## 4.1 OS. system () <br/> # system (), a very simple function that receives and executes system commands in the string format. When executing a command, python is suspended. <Br/> # After the execution is complete, the exit status is displayed in the format of system (), and the execution of Python continues. </P> <p> # system () retains the existing standard files, including standard output, it means that the output of any command and program display will be uploaded to the standard output. <br/>. Be careful here, because a specific application, such as the Public Gateway Interface (CGI), will output a string other than the valid <br/> # Text Markup Language (HTML, after sending standard output back to the client, a Web browser error may occur. <Br/> # system () is usually used together with commands that do not generate output. Some of these commands include programs that compress or convert files, hanging <br/> # program that loads the disk to the system, or other commands that execute a specific task-the exit status shows that the task is successful or failed, rather than entering <br/> # To communicate with/or output. The usual convention is to use exit status. 0 indicates success, and non-zero indicates other types of errors. </P> <p> # import OS <br/> # result = OS. system ('uname-a') <br/> # print (result) </P> <p >## 4.2 OS. popen () <br/> # the popen () function is a combination of file objects and system () functions. It works in the same way as system (), but it can establish <br/> # A one-way connection pointing to that program, and then access this program like accessing a file. If the program requires input, <br/> # Write the command in 'W' mode to call popen (). The data you send to the program will be received through standard input. Similarly, the 'R' <br/> # mode allows the spawn command. When it is written to the standard output, you can use the class file handle to use the familiar file pair <br/> # image read * () method to read the input. Just like for files, you should close () connection after use. </P> <p> # import OS <br/> # F = OS. popen ('uname-a') <br/> # DATA = f. readline () <br/> # F. close () <br/> # print (data) </P> <p> # ************ Part 5: end execution ***************** <br/> # exit after the program runs successfully and the statements at the highest level of all modules are executed, we call this a clean execution. <Br/> # in many cases, exit from Python in advance, such as a fatal error or failure to meet the conditions for continued execution. <Br/> # There are various methods to handle errors in Python. One of them is to handle exceptions and exceptions. Another method is <br/> # Build a "scanner" method, so that the main part of the code can be placed in the IF statement and executed without errors, <br/> # The error can be terminated "normally. However, sometimes the error code <br/> # is returned when you exit the calling program to indicate the event. </P> <p >## 5.1 sys. exit () and systemexit <br/> # exit the program immediately and return the exit () function in the SYS module. SYS. exit () Syntax: <br/> # sys. exit (status = 0) <br/> # When sys. systemexit () is thrown. Unless exceptions are monitored (in a try statement and <br/> # An appropriate limit t clause), exceptions are usually not caught or handled, the interpreter exits with the given status parameter. For example, if <br/> # is not given, the default value of this parameter is 0. System exit is the only exception that is not regarded as an error. It only indicates the desire to exit python <br/>. </P> <p> # SYS. Exit () is often used after an error is found in the middle of a command call. For example, if the parameter is incorrect, it is invalid, or the number of parameters is incorrect. </P> <p >## 5.2 sys. exitfunc () <br/> # sys. exitfunc () is unavailable by default, but you can rewrite it to provide additional functions. This function is used when SYS. Exit () is called and <br/> # is used before the interpreter exits. This function does not contain any parameters, so the function you created should also be <br/> # Without parameters. <Br/> # If sys. exitfunc has been overwritten by the previously defined exit function. The best way is to use this code as part of your exit () <br/> # function. Generally, the exit function is used to execute certain types of close activities, such as closing files and network connections <br/> #. It is recommended to complete maintenance tasks, such as releasing previously reserved system resources. </P> <p >## 5.3 OS. _ exit () and OS. _ exit () function <br/> # The _ exit () function of the OS module should not be used in general applications. (Platform-related, applicable only to specific platforms, such as UNIX <br/> #-based platforms and Win32 platforms ). Syntax: <br/> # OS. _ exit (Status) <br/> # functions provided by this function and SYS. exit () and SYS. exitfunc (). Instead, exit immediately without any cleanup. <br/> # python. Unlike SYS. Exit (), status parameters are required. Using SYS. Exit () is the preferred method to exit the interpreter. </P> <p >## 5.4 OS. Kill () <br/> # The kill () function of the OS module simulates traditional UNIX functions to send signals to processes. The kill () parameter is the process ID (PID) <br/> # And the signal you want to send to the process. The typical signal sent is SIGINT, sigquit, or, more thoroughly, sigkill to terminate the process. </P> <p>

Bytes -------------------------------------------------------------------------------------------------------
Blog: http://blog.csdn.net/tianlesoftware
WEAVER: http://weibo.com/tianlesoftware
Email: dvd.dba@gmail.com
Dba1 group: 62697716 (full); dba2 group: 62697977 (full) dba3 group: 62697850 (full)
Super DBA group: 63306533 (full); dba4 group: 83829929 (full) dba5 group: 142216823 (full)
Dba6 group: 158654907 (full) dba7 group: 69087192 (full) dba8 group: 172855474
DBA super group 2: 151508914 dba9 group: 102954821 chat group: 40132017 (full)
-- Add the group to describe the relationship between Oracle tablespace and data files in the remarks section. Otherwise, the application is rejected.

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.