时间循环

2024-07-01 07:51:34 发布

您现在位置: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()

我只关注信息


Tags: csvfromimportselfformatmessagedatafactory
1条回答
网友
1楼 · 发布于 2024-07-01 07:51:34

下面是Algo的小代码。你知道吗

算法:

  1. 设置保存数据的详细文件路径。你知道吗
  2. 从用户获取输入并处理创建列表。你知道吗
  3. 将数据保存到文件。你知道吗
  4. 等一段时间。你知道吗
  5. 删除文件。你知道吗

代码

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()获取python3.x的用户信息

使用raw_input()获取python2.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

相关问题 更多 >

    热门问题