Python 如何使用websocket多处理连接到多个通道?
我编写了一个脚本,允许通过不同的websockets频道收集数据,但我无法用这个脚本同时监听多个频道。我想找到一个解决方案,如“多处理”或“线程” 通过在不同的终端上运行多次脚本,我成功地收听了多个频道。 例如,如果我想收听10个频道,我会使用所需的频道作为输入参数启动10次脚本,但我确信必须有一种更聪明、更干净的方法来使用多进程或其他进程。 事实上,如果我启动到许多终端,我的电脑开始变得非常慢,这个程序的最终结果就是用一个比我的笔记本电脑功能弱的树莓Pi来运行它 脚本如下所示:Python 如何使用websocket多处理连接到多个通道?,python,websocket,python-multiprocessing,python-asyncio,python-multithreading,Python,Websocket,Python Multiprocessing,Python Asyncio,Python Multithreading,我编写了一个脚本,允许通过不同的websockets频道收集数据,但我无法用这个脚本同时监听多个频道。我想找到一个解决方案,如“多处理”或“线程” 通过在不同的终端上运行多次脚本,我成功地收听了多个频道。 例如,如果我想收听10个频道,我会使用所需的频道作为输入参数启动10次脚本,但我确信必须有一种更聪明、更干净的方法来使用多进程或其他进程。 事实上,如果我启动到许多终端,我的电脑开始变得非常慢,这个程序的最终结果就是用一个比我的笔记本电脑功能弱的树莓Pi来运行它 脚本如下所示: import
import websocket
import sys
def getData(uri, channel, pathCSV):
ws = websocket.create_connection(uri)
try:
print("Sending data")
ws.send(channel)
print("Receiving...")
result = ws.recv()
print ("Received '%s'" % result)
while True:
result = ast.literal_eval(ws.recv())
print("Received ast '%s'" % result)
# Here is a function which write the collected data to
# a CSV.
exportDataToCSV(result, pathCSV)
except websocket.WebSocketConnectionClosedException as e:
print('This caught the exception')
ws.close()
# In case of error I simply relaunch the script
getMarketData(uri, channel, pathCSV)
except KeyboardInterrupt:
ws.close()
return(result)
pathCSV = "/path/to/CSV"
uri = "websocket adress"
channelList = ["channel1", "channel2", "channel3", "channel4",
"channel5"]
#channel : for now I have to select one
while True:
getData(uri, channel, pathCSV)
因此,问题是“我如何在一个脚本实例中监听所有频道,该脚本用于收集接收到的数据并将其写入CSV?”
如果您有任何想法要分享,请提前向您表示感谢
编辑:
我在“asyncio”库中找到了一些信息,这些信息将我引向以下代码:
import asyncio
import websockets
import ast
uri = "websocket uri"
channelList = ["channel1", "channel2", "channel3", "channel4",
"channel5"]
async def getData(channelList):
uri = "websocket uri"
for channel in channelList:
async with websockets.connect(uri) as ws:
await ws.send(channel)
print("Receiving...")
result = await ws.recv()
# Confirmation ofsubscription
print ("Received '%s'" % result)
result = ast.literal_eval(await ws.recv())
# Getting Data
print("Received ast '%s'" % result)
asyncio.get_event_loop().run_until_complete(getData(channelList))
这样,我只需启动一个脚本就可以订阅和收听所有频道。
但这并没有真正的帮助,因为在每个循环中,我都必须重新连接到通道,如果一个通道需要很长时间才能回答,那么在我没有连接到其他通道的情况下,我会丢失很多其他通道的信息
有人能帮我优化流程吗