簡體   English   中英

為什么會出現“RuntimeError:此事件循環已在運行”?

[英]Why do I get "RuntimeError: This event loop is already running"?

我正在運行以下代碼,試圖從https://cdn.ime.co.ir獲取一些信息,但它給了我這個錯誤:

RuntimeError:此事件循環已在運行

我的代碼是:

import requests
import json
import asyncio
import websockets
import urllib
import random
from threading import Thread

connectionData = [{"name":"marketshub"}]

r = requests.get("https://cdn.ime.co.ir/realTimeServer/negotiate", params = {
    "clientProtocol": "2.1",
    "connectionData": json.dumps(connectionData),
})
response = r.json()

#print(f'got connection token : {response["ConnectionToken"]}')

wsParams = {
    "transport": "webSockets",
    "clientProtocol": "2.1",
    "connectionToken": response["ConnectionToken"],
    "connectionData": json.dumps(connectionData),
    "tid": random.randint(0,9)
}

websocketUri = f"wss://cdn.ime.co.ir/realTimeServer/connect?{urllib.parse.urlencode(wsParams)}"

def startReceiving(arg):
    r = requests.get("https://cdn.ime.co.ir/realTimeServer/start", params = wsParams)
    print(f'started receiving data : {r.json()}')

result = []

async def websocketConnect():
    async with websockets.connect(websocketUri) as websocket:
        print(f'started websocket')
        thread = Thread(target = startReceiving, args = (0, ))
        thread.start()
        for i in range(0,10):
            print("receiving")
            data = await websocket.recv()
            jsonData = json.loads(data)
            if ("M" in jsonData and len(jsonData["M"]) > 0 and "A" in jsonData["M"][0] and len(jsonData["M"][0]["A"]) > 0):
                items = jsonData["M"][0]["A"][0]
                if type(items) == list and len(items) > 0: 
                    result = items
                    break
        thread.join()
        print(json.dumps(result, indent=4, sort_keys=True))

asyncio.get_event_loop().run_until_complete(websocketConnect())

#print([i for i in result if i["ContractCode"] == "SAFOR99"])

為什么會收到此錯誤消息以及如何解決該問題?

編輯:這是 spyder IDE 中的完整錯誤消息......................:

Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 7.7.0 -- An enhanced Interactive Python.

runfile('C:/Users/m/Desktop/python/selen/auto_new.py', wdir='C:/Users/m/Desktop/python/selen')
Traceback (most recent call last):

  File "<ipython-input-1-6b5319e4825b>", line 1, in <module>
    runfile('C:/Users/m/Desktop/python/selen/auto_new.py', wdir='C:/Users/m/Desktop/python/selen')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/m/Desktop/python/selen/auto_new.py", line 52, in <module>
    asyncio.get_event_loop().run_until_complete(websocketConnect())

  File "C:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 571, in run_until_complete
    self.run_forever()

  File "C:\ProgramData\Anaconda3\lib\asyncio\base_events.py", line 526, in run_forever
    raise RuntimeError('This event loop is already running')

RuntimeError: This event loop is already running

您在 IPython 內核中。 不要在 IPython 內核中運行它。 不久前,他們改變了異步處理方式,打破了這種情況; 內核本身已經在事件循環中運行。 (終端 IPython 的工作方式略有不同,所以這可能仍然在終端中的 IPython 中工作,但我堅持直接通過 Python 運行它。)

使用以下命令安裝 twint:

:pip3 install --user --upgrade git+https.//github.com/twintproject/twint.git@origin/master#egg=twint

如果您使用的是 Colab。 這解決了問題或我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM