设为首页 收藏本站
查看: 1135|回复: 0

[经验分享] 上网计时【Python】

[复制链接]

尚未签到

发表于 2015-4-21 07:43:26 | 显示全部楼层 |阅读模式
  用 Python 写的一个记录上网用时的小脚本(自用),上网时间记录在 sqllite 数据库中
  通过访问某个网站来判断网络是否连接或断开


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import urllib2
import ConfigParser
import sqlite3
# 记录上网时长,并将数据写入到数据库
# 插入数据
def insert_data(xcur, start_time, end_time, total_time):
sql = 'INSERT INTO time(starttime, endtime, totaltime) VALUES (?, ?, ?)'
values = (start_time, end_time, total_time)
xcur.execute(sql, values) # 执行 SQL 语句
# 查询总上网时长
def query_sum(xcur):
xcur.execute('select sum(totaltime) as total from time')
total = xcur.fetchone()[0] # 获取单一结果集
return total
# 设置默认配置
def default_config( configs, configfile):
configs.add_section('General')
configs.set('General', 'URL', 'http://www.baidu.com/favicon.ico')
with open(configfile, 'wb') as config_file:
configs.write(config_file)
config_file.close()
CONFIGFILE = 'config.ini'  # 配置文件名称
config = ConfigParser.RawConfigParser()
# 获取配置文件中 URL 的值
while True:
try:
config.read(CONFIGFILE)
url = config.get('General', 'URL').decode('utf-8')
except:
default_config(config, CONFIGFILE)
else:
break
# 模拟浏览器
user_agent = 'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) \
Gecko/20100101 Firefox/4.0.1'
headers = { 'User-Agent' : user_agent }
request = urllib2.Request(url=url, headers=headers)
# dbfolder = 'DB' 一个文件夹(如果不存在则创建)保存数据库文件
# if not os.path.exists(dbfolder):
#    os.mkdir(dbfolder)
# dbfile = dbfolder + time.strftime('%Y_%m',time.localtime()) + '.db'
# 每个月一个数据库(e.g. 2011_05.db)
dbfile = time.strftime('%Y_%m',time.localtime()) + '.db'
isconnected = False  # 网络连接状态
starttime = endtime = None
sleep_time = 30 # 每次循环的间隔(秒)
while True:
try:
urllib2.urlopen(request)
except:# Exception, e:
# print e
# print isconnected
if isconnected: # 连接第一次断开
print 'end'
endtime = time.time()
# print endtime
totaltime = (endtime - starttime)/60.0 #以1分钟为单位计时
if totaltime%1 > 0:
totaltime = int(totaltime) + 1 # 结果舍弃秒数,秒入为分
print totaltime
starttime = time.strftime('%Y/%m/%d %H:%M:%S',
time.localtime(starttime)) #格式化日期
endtime = time.strftime('%Y/%m/%d %H:%M:%S',
time.localtime(endtime)) # 格式化日期
print starttime
print endtime
while True:
try:
conn = sqlite3.connect(dbfile)  # 连接数据库
cur = conn.cursor()  # 获取游标
insert_data(cur, starttime, endtime, totaltime) # 插入数据
total_month = query_sum(cur) # 获取当月中上网时间
except:# Exception, e:
# print e
# 建表
cur.execute('''
CREATE TABLE time (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT DEFAULT 1,
starttime TEXT,
endtime   TEXT,
totaltime REAL
)
''')
else:
break
finally:
conn.commit()  # 提交挂起的事务
cur.close() # 关闭游标
conn.close() # 关闭数据库连接
print u'当月总上网时间:%s 分钟(%.2f 小时)' % (total_month, total_month/60.0)
# pass
isconnected = False # 标记连接状态为断开
else:
# print 'ok'
if not isconnected: # 第一次连接
print 'start'
starttime = time.time()
# print starttime
isconnected = True
# print isconnected
# pass
time.sleep(sleep_time) # 每过一段时间(秒)循环一次

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-58997-1-1.html 上篇帖子: Python识别验证码的开源工具 下篇帖子: 使用python调用weibo api
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表