我是python编程的新手。我有个问题。我想每15分钟保存一次输入数据(原始数据到列表)。 15分钟后,列表将被删除并再次写入输入数据。任何人都可以帮助我吗?谢谢你的善意。
from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
def WriteListtoCSV (data):
with open ('tesdata.csv','a') as csvfile:
writer=csv.writer(csvfile)
for val in data:
writer.writerow([val])
class MyServerProtocol(WebSocketServerProtocol):
def onConnect(self, request):
print("Client connecting: {0}".format(request.peer))
def onOpen(self):
print("WebSocket connection open.")
def onMessage(self, payload, isBinary):
if isBinary:
print("Binary message received: {0} bytes".format(len(payload)))
else:
print("Text message received: {0}".format(payload.decode('utf8')))
# echo back message verbatim
self.sendMessage(payload, isBinary)
mins = 0
data_nilai = [ ]
while mins != 60: #change value with seconds
data_nilai.append(payload.decode('utf8'))
time.sleep(1)
mins+=1
WriteListtoCSV(data_nilai)
#ClearCSV()
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {0}".format(reason))
if __name__ == '__main__':
import sys
import csv
import time
from twisted.python import log
from twisted.internet import reactor
log.startLogging(sys.stdout)
factory = WebSocketServerFactory(u"ws://192.168.1.23:9000", debug=False)
factory.protocol = MyServerProtocol
# factory.setProtocolOptions(maxConnections=2)
reactor.listenTCP(9000, factory)
reactor.run()
我的重点只是onMessage
答案 0 :(得分:1)
以下是Algo的小代码。
<强> ALGO 强>:
<强>代码强>:
import pickle
import time
import os
detail_file = "/tmp/test.txt"
while(1):
# Get input from User and split to List.
user_input = raw_input("Enter item of the list separated by comma:")
user_input = user_input.split(",")
print "User List:- ", user_input
#- Save process, We can save your data i.e. list into file or database or any where
with open(detail_file, "wb") as fp:
pickle.dump(user_input, fp)
# Wait for 15 minutes.
time.sleep(900) # 15 * 60 = 900
# delete Save details.
os.remove(detail_file)
注意强>:
使用input()
获取 Python 3.x
使用raw_input()
获取 Python 2.x
[编辑1]
<强> crontab的强>
参考:http://www.thegeekstuff.com/2011/07/cron-every-5-minutes/
参考:http://www.computerhope.com/unix/ucrontab.htm
操作系统:CentOS
要编辑crontab,请使用以下命令:
crontab -e
*/15 * * * * python /tmp/script.py
其中crontab条目结构为:
m h dom mon dow command