3

我正在使用 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()
4

1 回答 1

5

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 不会自行将其放在那里

于 2018-01-03T08:09:10.347 回答