【发布时间】:2012-05-17 19:02:38
【问题描述】:
我有兴趣构建一个 python 脚本,它可以为我提供关于每个间隔(可能是一分钟)写入文件的行数的统计信息。我有在数据进入时正在写入的文件,每个用户都有一个新行,通过外部程序传递数据。知道每个 x 有多少行给了我一个可以用于未来扩展计划的指标。输出文件由行组成,所有行的长度都相对相同,并且最后都带有行返回。我正在考虑编写一个脚本,该脚本执行以下操作:在特定点测量文件的长度,然后在未来的另一个点再次测量它,减去两者并得到我的结果......但我不知道如果这是理想的,因为测量文件的长度需要时间,这可能会扭曲我的结果。有没有人有其他想法?
根据人们的说法,我把它放在一起开始:
import os
import subprocess
import time
from daemon import runner
#import daemon
inputfilename="/home/data/testdata.txt"
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/count.pid'
self.pidfile_timeout = 5
def run(self):
while True:
count = 0
FILEIN = open(inputfilename, 'rb')
while 1:
buffer = FILEIN.read(8192*1024)
if not buffer: break
count += buffer.count('\n')
FILEIN.close( )
print count
# set the sleep time for repeated action here:
time.sleep(60)
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
它的工作是每 60 秒获取一次计数并将其打印到屏幕上,我的下一步是我猜的数学。
另一个编辑:我以一分钟的间隔添加了计数的输出:
import os
import subprocess
import time
from daemon import runner
#import daemon
inputfilename="/home/data/testdata.txt"
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty'
self.pidfile_path = '/tmp/twitter_counter.pid'
self.pidfile_timeout = 5
def run(self):
counter1 = 0
while True:
count = 0
FILEIN = open(inputfilename, 'rb')
while 1:
buffer = FILEIN.read(8192*1024)
if not buffer: break
count += buffer.count('\n')
FILEIN.close( )
print count - counter1
counter1 = count
# set the sleep time for repeated action here:
time.sleep(60)
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
【问题讨论】:
-
线条的大小是否相同或非常相似?虽然计算一个非常大的文件中的行数需要很长时间,但查找文件的大小要快得多。
-
您是否能够编辑正在写入数据的程序?你可以修改它,让它定期报告它写了多少行。
-
线条有些相似,例如姓名、地址等...但是如果该人写得更多,则某些调查问题的答案会更长...但是我同意找到平均线条大小和文件大小和一些设计可能是要走的路......我没有能力修改输入程序,但我可以与编写它的人交谈并询问他们是否可以。
-
无论您最终得到什么解决方案,我都建议您针对专门的软件(例如 wc)进行计时。