循环使用时间Python

时间:2015-09-25 06:20:22

标签: python

我是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

1 个答案:

答案 0 :(得分:1)

以下是Algo的小代码。

<强> ALGO

  1. 设置我们保存数据的详细文件路径。
  2. 从用户获取输入并创建列表进程。
  3. 将数据保存到文件。
  4. 等一段时间。
  5. 删除文件。
  6. <强>代码

    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