简体   繁体   English

一分钟运行一次Python函数

[英]Run Python Function Every Second for A Minute

I recently started learning Python and I have an application for it where I would like to create a text file that records data every two seconds for a minute, and then begins again with a new file. 我最近开始学习Python,并且有一个应用程序,我想要创建一个文本文件,该文件每两秒钟记录一次数据,然后以一个新文件重新开始。 I have it written where the opened file is formatted for SQL and SQL INSERT queries are being added on. 我已将其写入为SQL格式化打开的文件的位置,并添加了SQL INSERT查询。

The trouble I am having is creating the code to actually work properly. 我遇到的麻烦是创建代码以使其正常工作。 The Python itself is working fine for just inserting a new line of SQL to the already opened file, but the output looks like this: 仅在已打开的文件中插入新的SQL行,Python本身就可以正常工作,但是输出如下所示:

[blank line is here because of the \n]
INSERT INTO table (column 1, column 2) VALUES ('7113', '1337');
INSERT INTO table (column 1, column 2) VALUES ('7113', '1337');

My issue is that I need to get the data so there is no new line at the top and no semicolon at the last row. 我的问题是我需要获取数据,因此顶部没有新行,最后一行没有分号。

This is my source: 这是我的来源:

from threading import Timer
import time

def start():
    t = Timer(1.0,start)

    foo = "7113"
    bar = "1337"
    date = time.strftime('%Y-%m-%d %H:%M:%S')
    sql = "\nINSERT INTO table (column 1, column 2) VALUES ('%s', '%s');" % (foo, bar)

    query = open(date + ".sql", "a")
    query.write(sql)
    query.close()
    t.start()

start()

Since I'm not the best with language, a simpler version of what I want to do is: 由于我对语言的了解不是最好的,所以我想做的一个简单的版本是:

  1. Have one function run the first code, spitting out INSERT INTO table (column 1, column 2) VALUES ('7113', '1337'); 让一个函数运行第一个代码,吐出INSERT INTO table (column 1, column 2) VALUES ('7113', '1337'); without the extra line in front but with a semicolon. 前面没有多余的行,但带有分号。
  2. Have another function run 58 times, adding lines with \\n before the SQL query and the semicolon after. 让另一个函数运行58次,在SQL查询之前用\\n添加行,在SQL查询之后添加分号。
  3. Have the last function run the 60th time, including the \\n but without the semicolon. 让最后一个函数运行第60次,包括\\n但不带分号。
  4. Close the current file and generate a new text file with the timestamp just for that minute, like 2013-07-09 12-30-00.sql and repeat the process over again for 2013-07-09 12-31-00.sql , and so on. 关闭当前文件,并为该分钟生成一个带有时间戳的新文本文件,例如2013-07-09 12-30-00.sql并再次对2013-07-09 12-31-00.sql重复该过程, 等等。

I imagine there is a lot more after that, like getting a PHP or Python script to read the date and execute it, or I could just have all of them executed and then order the table ascending. 我想在那之后还有很多事情,比如让PHP或Python脚本读取日期并执行它,或者我可以全部执行它们,然后将表升序排列。 However, that can be solved and researched at a later date. 但是,可以稍后解决和研究。 I just want to get this working since I've been searching for a few hours now on how to do it and I couldn't find anything helpful. 我只想开始工作,因为我已经搜索了几个小时了,但是找不到任何有用的方法。 I'm sure the answer is something obvious, though. 我敢肯定,答案是显而易见的。

Thanks for reading and I hope you guys can help! 感谢您的阅读,希望你们能为您提供帮助! I've used this website a bunch now for helpful tidbits and it's fantastic. 我现在已经使用了该网站很多有用的花絮,这太棒了。 Whoever came up with this needs to be praised a bunch. 谁想出这一点,都应该受到赞扬。

Also, if anyone has any useful resources for learning Python (I learned through Codecademy ), I would really appreciate them. 另外,如果任何人都有学习Python的有用资源(我是通过Codecademy学习的),我将不胜感激。 This is so much more fun than learning C++. 这比学习C ++有趣得多。

I solved the problem by having a global counting variable and using if and elif statements. 我通过具有global counting变量并使用ifelif语句解决了该问题。 Currently the script is functioning every 500ms with no problem. 当前,脚本每500毫秒运行一次,没有问题。 If anyone wants to see my code, here it is: 如果有人想看我的代码,这里是:

Commented version because syntax highlighting here with comments is screwing up for whatever reason. 带注释的版本,因为无论出于何种原因,此处带有注释的语法突出显示都在搞砸。

from threading import Timer
import xml.etree.ElementTree as ET
import urllib
import time

datetime = time.strftime('%Y-%m-%d %H.%M')
filename = datetime + ".sql"
url = "localhost/send.cgi"
interval = 0.5
table_name = "0001"
columns = "(time, foo, bar)"
counting = 0 

def parser():
    t = Timer(interval, parser)
    global counting
    global filename
    query = open(filename, "a")

    if counting == 0:
        date = int(time.time()*1000)
        web = urllib.urlopen(url)
        tree = ET.parse(web)
        root = tree.getroot()
        foo = root[1].text.replace(" ", "")
        bar = root[2].text.replace(" ", "")
        sql = "INSERT INTO %s %s VALUES ('%s', '%s', '%s');" % (table_name, columns, date, foo, bar)
        counting += 1
        query.write(sql)
        print counting
        t.start()
    elif (counting > 0) and (counting < 59):
        date = int(time.time()*1000)
        web = urllib.urlopen(url)
        tree = ET.parse(web)
        root = tree.getroot()
        foo = root[1].text.replace(" ", "")
        bar = root[2].text.replace(" ", "")
        sql = "\nINSERT INTO %s %s VALUES ('%s', '%s', '%s');" % (table_name, columns, date, foo, bar)
        counting += 1
        query.write(sql)
        print counting
        t.start()
    elif counting == 59:
        date = int(time.time()*1000)
        web = urllib.urlopen(url)
        tree = ET.parse(web)
        root = tree.getroot()
        foo = root[1].text.replace(" ", "")
        bar = root[2].text.replace(" ", "")
        sql = "\nINSERT INTO %s %s VALUES ('%s', '%s', '%s')" % (table_name, columns, date, foo, bar)
        counting += 1
        query.write(sql)
        print counting
        t.start()
    elif counting == 60:
        query.close()
        datetime = time.strftime('%Y-%m-%d %H-%M')
        filename = datetime + ".sql"
        counting = 0
        t.start()
parser()

If any improvements can be made, I would love to see them! 如果可以进行任何改进,我很乐意看到它们! <3 This code is meant for a certain kind of web server, though. <3但是,此代码是针对某种Web服务器的。 It may require some modifications to work. 可能需要进行一些修改才能起作用。 What the web server does is, when requested, sends a virtual XML file (which is just data, not the file) and this code requests it, interprets it, and shoots it into a .sql file so I can later execute them into a table to something. Web服务器要做的是,在被请求时发送一​​个虚拟XML文件(它只是数据,而不是文件),并且此代码请求它,对其进行解释并将其射入一个.sql文件,以便以后可以将它们执行为表到东西。 In the end, the code will grab over ten different columns of data and create the file for an hour, which is 7200 half-seconds. 最后,该代码将捕获十个不同的数据列,并创建一个小时的文件,即7200半秒。

Enjoy! 请享用!

EDIT: Yay, apparently the SQL syntax doesn't work. 编辑:是的,显然SQL语法不起作用。 Troubleshooting. 故障排除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM