Coroutine achieve multi-tasking asynchronous

Import ASYNCIO
 Import Time 
headers = {
     ' the User-- Agent ' : ' the Mozilla / 5.0 (the Linux; the Android 6.0; the Nexus. 5 the Build / MRA58N) AppleWebKit / 537.36 (KHTML, like the Gecko) the Chrome / 77.0.3865.90 Mobile Safari / 537.36 ' 
} 
the async DEF Request (url):
     Print ( " downloading S% " % url)
     # asynico encountered in blocking operation must be performed manually suspend 
    the await asyncio.sleep (4) # the time.sleep (4) asynchronous synchronization occurs if the coroutine module-related code, can not be achieved asynchronous 
    Print ( " downloaded " , url) 
urls= [ " URL1 " , ' URL2 ' , ' urls3 ' ]
 # task list: storing a plurality of task objects 
Tasks = []
 for URL in URLs: 
    C = Request (URL) 
    Task = asyncio.ensure_future (C) 

    tasks.append ( task) 
Loop = asyncio.get_event_loop ()
 # fixed syntax: task list asyncio.wait encapsulated in 
loop.run_until_complete (asyncio.wait (tasks))

 

Guess you like

Origin www.cnblogs.com/Jnhnsnow/p/11617966.html