Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将websocket推送api输出写入文本文件?_Python_Python 2.7_Websocket_Poloniex - Fatal编程技术网

Python 如何将websocket推送api输出写入文本文件?

Python 如何将websocket推送api输出写入文本文件?,python,python-2.7,websocket,poloniex,Python,Python 2.7,Websocket,Poloniex,我正在使用python脚本从加密货币交换Poloniex上的订单簿获取实时更新 目前它将websocket推送到标准输出的信息打印出来,我需要做什么才能将其打印到文件中呢?我正在使用python-2.7,提前谢谢 下面是我正在使用的脚本: #!/usr/bin/python import sys, getopt import websocket import thread import time import json try: opts, args = getopt.getopt(s

我正在使用python脚本从加密货币交换Poloniex上的订单簿获取实时更新

目前它将websocket推送到标准输出的信息打印出来,我需要做什么才能将其打印到文件中呢?我正在使用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内置了对文件操作的支持:

您可以执行以下操作,而不是打印(消息):

file_path = '/example/file.txt' #choose your file path
with open(file_path, "w") as output_file:
    output_file.write(message + "\n")

请注意,
+“\n”
是这样的,每个消息都将写入文件中的新行,因为python不会自己将其放在那里

谢谢您的帮助,有了它,我现在可以将输出重定向到一个文件。但是文件被截断了。。。因此,只有API推送的最后一条消息保留在文件中。您可以使用“a”而不是“w”将其打开,以附加而不是覆盖这允许您同时订阅多对吗?