python - Python 时间循环

标签 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()

我的重点只是消息

最佳答案

以下是带有小代码的 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()获取Python 3.x的用户信息

使用raw_input()获取Python 2.x的用户信息

[编辑 1]

定时任务

引用号: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

关于python - Python 时间循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32775995/

相关文章:

Python形态学n_ary_converter

Python 全局变量不更新

python - 将轮廓转换为 BLOB OpenCV

python - 从统计文件中构建计数字典

python - 禁用 iPython Notebook 自动滚动

嵌套字典列表的 Python 平均列表

python - 为什么模型甚至不能预测正弦

python - Celery 的 pytest 装置在 http 请求期间无法按预期工作

python - 如何在 Pandas 中按对象分组应用滚动功能

python - tkinter - 显示帧后运行函数