[英]How can I connect to two different projects in Google BigQuery in Python?
[英]Can I connect to two different websockets servers simultaneously in python?
我需要使用python同時連接到兩個websockets服務器,因為我需要將從每個接收到的數據合並到一個文件中,然后進行處理。 我已經對一個websockets feed成功地使用了以下類似的方法,但是不能同時用於兩個feed:
from websocket import create_connection
ws_a = create_connection("wss://www.server1.com")
ws_a.send("<subscription message, server 1>")
ws_b = create_connection("wss://www.server2.com")
ws_b.send("<subscription message, server 2>")
while bln_running:
response_a = ws_a.recv()
if "success" in response_a:
...do something...
response_b = ws_b.recv()
if "success" in response_b:
...do something...
但是,在此示例中,我僅從服務器1接收事件。我不認為將其拆分為兩個線程是可行的,因為這樣我將擁有兩組不同的數據,因此需要將它們合並。 (盡管挑戰此聲明是一種可能的替代解決方案???)
有關同時獲得兩個供稿的任何指導或建議。
非常感謝。
我的python版本:3.6.2 | Anaconda自定義(64位)| (默認值,2017年9月19日,08:03:39)[MSC v.1900 64位(AMD64)]
這工作:
from websocket import create_connection
from threading import Lock, Thread
lock = Lock()
message_list = [] #global list
def collect_server1_data():
global message_list
bln_running = True
ws_a = create_connection("wss://www.server1.com")
ws_a.send("<subscription>")
while bln_running:
response_a = ws_a.recv()
lock.acquire()
message_list.append(response_a)
lock.release()
response_a = ""
def collect_server2_data():
global message_list
bln_running = True
ws_b = create_connection("wss://www.server2.com")
ws_b.send("<subscription>")
while bln_running:
response_b = ws_b.recv()
lock.acquire()
message_list.append(response_b)
lock.release()
response_b = ""
### --------Main--------
threads = []
for func in [collect_server1_data, collect_server2_data]:
threads.append(Thread(target=func))
threads[-1].start()
for thread in threads:
thread.join()
感謝JohanL的正確指導。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.