如何将 websocket push api 输出写入文本文件?
How to write websocket push api output to text file?
我正在使用 python 脚本从加密货币交易所 Poloniex 的订单簿中获取实时更新。
目前是将websocket推送的信息打印到stdout,我需要怎么做才能打印到文件中呢?我正在使用 python-2.7,提前致谢!
下面是我正在使用的脚本:
#!/usr/bin/python
import sys, getopt
import websocket
import thread
import time
import json
try:
opts, args = getopt.getopt(sys.argv[1:], 'p:', ['parity='])
except getopt.GetoptError:
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--paridade'):
parity = arg
else:
sys.exit(2)
data = {'command':'subscribe','channel':''+parity+''}
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
print("ONOPEN")
def run(*args):
ws.send(json.dumps(data))
while True:
time.sleep(1)
ws.close()
print("thread terminating...")
thread.start_new_thread(run, ())
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://api2.poloniex.com/",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
python 内置了对文件操作的支持:https://docs.python.org/2/library/stdtypes.html#bltin-file-objects
代替print(message)
你可以这样做:
file_path = '/example/file.txt' #choose your file path
with open(file_path, "w") as output_file:
output_file.write(message + "\n")
请注意,+ "\n"
是为了让每条消息都写入文件中的新行,因为 python 不会将其单独放在那里
我正在使用 python 脚本从加密货币交易所 Poloniex 的订单簿中获取实时更新。
目前是将websocket推送的信息打印到stdout,我需要怎么做才能打印到文件中呢?我正在使用 python-2.7,提前致谢!
下面是我正在使用的脚本:
#!/usr/bin/python
import sys, getopt
import websocket
import thread
import time
import json
try:
opts, args = getopt.getopt(sys.argv[1:], 'p:', ['parity='])
except getopt.GetoptError:
sys.exit(2)
for opt, arg in opts:
if opt in ('-p', '--paridade'):
parity = arg
else:
sys.exit(2)
data = {'command':'subscribe','channel':''+parity+''}
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
print("ONOPEN")
def run(*args):
ws.send(json.dumps(data))
while True:
time.sleep(1)
ws.close()
print("thread terminating...")
thread.start_new_thread(run, ())
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://api2.poloniex.com/",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
python 内置了对文件操作的支持:https://docs.python.org/2/library/stdtypes.html#bltin-file-objects
代替print(message)
你可以这样做:
file_path = '/example/file.txt' #choose your file path
with open(file_path, "w") as output_file:
output_file.write(message + "\n")
请注意,+ "\n"
是为了让每条消息都写入文件中的新行,因为 python 不会将其单独放在那里