简体   繁体   中英

Python asyncio error

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.

我可以在Ubuntu 16.04上运行您的代码而没有任何问题。我认为这是Windows信号处理程序的问题。Windows没有信号,并解决了您的代码是否应以其他方式退出控制台和GUi程序。阅读更多控制台控制处理程序

尝试将网址更改为例如http://www.google.com并将Python更新为最新版本。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM