我使用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()
答案 0 :(得分:3)
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不会将它自己放在那里