I tried to run the following program in Python 3.6.4
import asyncio
import concurrent.futures
import requests
async def main():
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
loop = asyncio.get_event_loop()
futures = [
loop.run_in_executor(
executor,
requests.get,
'http://example.org/'
)
for i in range(20)
]
for response in await asyncio.gather(*futures):
pass
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
However, I got an error, saying that RuntimeError: This event loop is already running.
Here is the complete error message:
Traceback (most recent call last):
File "<ipython-input-1-28cf105e6739>", line 1, in <module>
runfile('C:/asyncio_test.py', wdir='C:/')
File "c:\program files\python36\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "c:\program files\python36\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/asyncio_test.py", line 30, in <module>
loop.run_until_complete(main())
File "c:\program files\python36\lib\asyncio\base_events.py", line 454, in run_until_complete
self.run_forever()
File "c:\program files\python36\lib\asyncio\base_events.py", line 408, in run_forever
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
I then tried to run the program in Ubuntu 16.10
File "asyncio_test.py", line 18
for response in await asyncio.gather(*futures):
^
SyntaxError: invalid syntax
How to solve the problem?
Thank you very much.