Я выполняю следующий код, который пытается получить некоторую информацию от https://cdn.ime.co.ir, но он выдает мне эту ошибку:
RuntimeError: Это событие l oop уже запущен
Мой код:
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