为什么我会得到“RuntimeError:此事件循环已在运行”?

2024-09-28 16:22:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行以下代码,试图从https://cdn.ime.co.ir获取一些信息,但它给了我这个错误:

RuntimeError: This event loop is already running

我的代码是:

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

Tags: runinpyimportloopeventasynciojson
1条回答
网友
1楼 · 发布于 2024-09-28 16:22:41

你在IPython内核中。不要在IPython内核中运行这个。他们不久前以某种方式打破了这种局面;内核本身已经在事件循环中运行。(终端IPython的工作方式有点不同,因此在终端的IPython中仍然可以工作,但我坚持直接通过Python运行它。)

相关问题 更多 >