Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Python 3.5 await / async     - Brief Linux commands (Linux)

- Firewall types and instructions (Linux)

- Ubuntu how to install and use Objective-C (Linux)

- Use Visual Studio to compile and use WinGDB remote debugging embedded Linux programs (Programming)

- IIS virtual host of safety knowledge (Linux)

- Ubuntu 14.04 next upgrade to GNOME 3.12 (Linux)

- PHP call a Python program (Programming)

- CentOS install SystemTap-2.6 (Linux)

- Shell Scripting Interview Questions (Programming)

- Tip: Use Cryptsetup U disk encryption (Linux)

- S5PV210 development board for embedded development environment to build under Ubuntu (Linux)

- RedHat Linux 6.4 installation RTL8188CUS wireless network card driver (Linux)

- Understand the security restore accidentally deleted critical system files (Linux)

- Ubuntu 15.04 installation MATE 1.10 (Linux)

- The difference between Linux su and sudo commands (Linux)

- Sublime Text Add instructions to insert the current time zone (Linux)

- Linux system security configuration (Linux)

- Cobbler automatic mass deployment of CentOS 6 and CentOS 7 (Linux)

- grep command Series: How to Use the grep command in Linux / UNIX (Linux)

- Use ISO document production OpenStack used CoreOS mirror (Linux)

 
         
  Python 3.5 await / async
     
  Add Date : 2016-06-02      
         
         
         
  PEP-0492 recently adopted in dealing with the Python 3.5 coroutine adds some special syntax. A large part of the new features in version 3.5 before it already has, but before the grammar is not the best, because the concept of generators and coroutines are somewhat mixed. PEP-0492 by using async keyword generators and coroutines make a distinction display.

This article aims to explain these new mechanisms underlying how this works. If you are just interested in how to use these features, then I suggest that you can ignore this article, but to see what the document built asyncio module. If you are interested in the underlying concepts underlying functionality of these concerns how to build your own asyncio module, you will have found this article interesting.

In this paper, we will completely give up any asynchronous I / O method, but only limited interaction using multiple coroutines. Here are two small functions:
def coro1 ():
    print ( "C1: Start")
    print ( "C1: Stop")


def coro2 ():
    print ( "C2: Start")
    print ( "C2: a")
    print ( "C2: b")
    print ( "C2: c")
    print ( "C2: Stop")

We started two of the most simple functions, coro1 and coro2. We can in order to perform two functions:
coro1 ()
coro2 ()

We get the expected output:
C1: Start
C1: Stop
C2: Start
C2: a
C2: b
C2: c
C2: Stop

However, for some reason, we may expect the code run interactively. Common functions can not do that, so we put these function into Ctrip:
async def coro1 ():
    print ( "C1: Start")
    print ( "C1: Stop")


async def coro2 ():
    print ( "C2: Start")
    print ( "C2: a")
    print ( "C2: b")
    print ( "C2: c")
    print ( "C2: Stop")

Through the new async keyword magic, these functions are no longer function, and now they become coroutines (more accurate to say that local coroutine function). When an ordinary function is called, the function is executed experience, but calling coroutine function, the function body will not be executed, you get a coroutine objects:
c1 = coro1 ()
c2 = coro2 ()
print (c1, c2)

Output:


(Interpreter will print warning messages when running, first ignored).

Why, then, have a coroutine objects? How to execute the code in the end? One way to do is to use the coroutine await expression (using the new await keyword). You might want to, you can do it this way:
await c1

However, you will certainly be disappointed. await expression only in a local function in the coroutine is valid. You must do this:
async def main ():
    await c1

Then the question is, main functions and how it started?

The key point is indeed a coroutine with Python generators are very similar, but also has a send method. We can start the execution of a coroutine by calling the send method.
c1.send (None)

We will first execute a coroutine can finally complete, but we also got a nasty StopIteration exception:
C1: Start
C1: Stop
Traceback (most recent call last):
  File "test3.py", line 16, in
    c1.send (None)
StopIteration

StopIteration exception is a markup generator (or, as here, coroutines) mechanism to implement end. Although this is an exception, but indeed our expectations! We can use a suitable try-catch code package it up, so you can avoid error. Next we make our second coroutine also execute:
try:
    c1.send (None)
except StopIteration:
    pass
try:
    c2.send (None)
except StopIteration:
    pass

Now we have all of the output, but a bit disappointing is that with the initial output was doing anything different. So we added a lot of code, but has not done alternately executed. Coroutine thread similarities or may alternate between multiple threads of execution, but differs in that the thread switching between coroutines is explicit, and the thread is better (In most cases implicit way). So we need to add the code to explicitly switch.

Typically Builder send method runs until abandon execution by keyword yield, maybe you think we can change coro1 like this:
async def coro1 ():
    print ( "C1: Start")
    yield
    print ( "C1: Stop")

But we can not use yield in coroutine inside. As an alternative, we can use the new expression to await suspend coroutine until awaitable execution ends. So we need the code similar to await _something_; here _something_ question is what is it? We must await something, rather than empty! The PEP explains what may await the (awaitable). One of them is another local coroutines, but this is for us to understand the underlying details are not what help. Another object defined by specific CPython API, but we do not intend to introduce expansion modules, but only limited to the use of pure Python. In addition, the remaining two options: coroutine object based on the generator, or a special Future of similar objects.

Next, we will choose the coroutine object based on generator. Basically a Python generator (for example: there is a yield function expression) may be labeled by types.coroutine decorated as a coroutine. So, this is one of the most simple example:
@ Types.coroutine
def switch ():
    yield

This defines a function coroutine-based generator. To get coroutine objects based builder, you only need to perform this function. We can modify our coro1 coroutine as follows:
async def coro1 ():
    print ( "C1: Start")
    await switch ()
    print ( "C1: Stop")

Through the above changes, we can expect coro1 and coro2 interleaved. So far, the output is like this:
C1: Start
C2: Start
C2: a
C2: b
C2: c
C2: Stop

I did not see, as expected, after the first print statement, coro1 stop the execution, coro2 then executed. In fact, we can see the following code coroutine how objects are suspended execution:
print ( "c1 suspended at: {}: {}". format (c1.gi_frame.f_code.co_filename, c1.gi_frame.f_lineno))

It can print line await expression is located. (Note: Print is the outermost await, so here are examples only, usually less useful).

The question now is how to make coro1 proceed finished yet? We can once again call send, the following code:
try:
    c1.send (None)
except StopIteration:
    pass
try:
    c2.send (None)
except StopIteration:
    pass
try:
    c1.send (None)
except StopIteration:
    pass

As expected with the resulting output:
C1: Start
C2: Start
C2: a
C2: b
C2: c
C2: Stop
C1: Stop

Currently, we have adopted a different coroutine explicit call to send them all to end execution. Under normal circumstances, this approach is not very good. Our hope is to have a function to control all coroutines run until all coroutines perform complete. In other words, we expect continuous call to send, to drive different coroutine execution until send raise StopIteration.

To do this we create a new function that passing a coroutine list, perform these functions coroutine until all over. We now have to do is call this function.
def run (coros):
    coros = list (coros)

    while coros:
        # Duplicate list for iteration so we can remove from original list.
        for coro in list (coros):
            try:
                coro.send (None)
            except StopIteration:
                coros.remove (coro)

This code each taking a coroutine coroutine execution from the list, if caught StopIteration exception, put the coroutine removed from the queue.

Next, we manually call send code to remove the code is as follows:
c1 = coro1 ()
c2 = coro2 ()
run ([c1, c2])

In summary, in Python 3.5, we can now await and async new functions easily coroutine execution. The relevant code for this article can be found on github.
     
         
         
         
  More:      
 
- Install apr support for Tomcat on Linux (Server)
- CentOS 6.5 using Virtualenv under development environment to build Python3 (Linux)
- To teach you a trick to find the real IP address (Linux)
- ORA-27054 NFS problem solving (Database)
- Linux environment to build next Cocos2dx-3.3.1 (Linux)
- 5 interesting Linux command line tips (Linux)
- Install Apache streaming media services on CentOS 6.4 (Server)
- MySQL function: group_concat () function (Database)
- Generated characters using Java Videos (Programming)
- Storm how to assign tasks and load balancing (Programming)
- OpenSSH version smooth upgrade method (Linux)
- N1QL bring SQL-like query NoSQL database experience (Database)
- Command filter MySQL slow query log (Database)
- using the ssh command to check the socket / Network Connections (Linux)
- Quick Install software RAID on Linux (Linux)
- The Samba service does not have permission to access (Server)
- ASP.NET 5 tutorial series (Server)
- Linux log management tools Logrotate (Linux)
- How to Install Linux kernel 4.0 on Ubuntu / CentOS (Linux)
- Ubuntu 15.04 install Complete Guide (Linux)
     
           
     
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.