应用界面
cxk.ico
库
安装pipenv
pip install pipenv -i https://pypi.doubanio.com/simple
自定义文件夹
set WORKON_HOME =
set WORKON_HOME = D:\CXK\cxk_python\all_system\Network_speed_monitoring
进入文件夹安装虚拟环境
pipenv install
上面这句出现错误时:AttributeError: 'NoneType' object has no attribute 'version_sort',原因python编译器的未知
pipenv install --python="C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python.exe"
进入虚拟环境命令行
pipenv shell
安装所需库
pip install PyQt5==5.15.0 -i https://pypi.doubanio.com/simple && pip install pyinstaller -i https://pypi.doubanio.com/simple && pip install psutil -i https://pypi.doubanio.com/simple && pip install qtpy -i https://pypi.doubanio.com/simple
打包
pyinstaller --distpath main/ -F -w -i cxk.ico --clean networkSpeedMonitoring.py -p utils.py -p dayData.py
退出pipenv
exit
提示
这是以前写的一款小应用(python百行代码自制电脑端网速悬浮窗),只不过这个是最近又重新优化一边的,作为我个人日常使用的软件,每天使用流量自动写入数据库统计。
代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/04/29 16:50
# @Author : Cxk
import json,os,time
import datetime, random
import time
import configparser
def getTimeNow(flag):
"""[summary]
时间获得工具
Args:
flag ([string]): [s 返回秒时间戳 ms 毫秒时间戳 time 返回格式化当前时间(小时) 其他 格式化时间(日)]
Returns:
[type]: [时间字符串]
"""
now = time.time() #返回float数据
if flag=='s':
# 获取当前时间戳---秒级级
return int(now)
elif flag =='ms':
#毫秒级时间戳
return int(round(now * 1000))
elif flag == "time":
# 格式化時間
return time.strftime('Time_%Y-%m-%d_%H%M%S',time.localtime(time.time()))
elif flag == "now":
# 格式化時間
return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
else:
return time.strftime('%Y-%m-%d',time.localtime(time.time()))
def timeToStr(format_time):
# 大于86400说明超过两天
# 格式化时间
format_time = format_time+' 00:00:00'
# 时间
ts = time.strptime(format_time, "%Y-%m-%d %H:%M:%S")
# 格式化时间转时间戳
return time.mktime(ts)
def judgeTime(startTime,endTime):
# 范围时间
d_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + startTime, '%Y-%m-%d%H:%M')
d_time_1 = datetime.datetime.strptime(str(datetime.datetime.now() + datetime.timedelta(days=0)).split(' ')[0] + endTime, '%Y-%m-%d%H:%M')
# 当前时间
n_time = datetime.datetime.now()
# 判断当前时间是否在范围时间内
if n_time > d_time and n_time < d_time_1:
return True
else:
return False
def timeAll(nextTime,today):
"""
返回离未来某个时间节点的时间秒数,today 今天时间节点,0是明天,1是今天
参数:16:00,0/1
"""
if today:
nowTime = time.time()
ts = time.strptime(str(datetime.datetime.now().date())+' '+nextTime+':00', "%Y-%m-%d %H:%M:%S")
# 格式化时间转时间戳
nextTime = time.mktime(ts)
return int(nextTime-nowTime)
else:
nowTime = time.time()
ts = time.strptime(str((datetime.datetime.now()+datetime.timedelta(days=-1)).date())+' '+nextTime+':00', "%Y-%m-%d %H:%M:%S")
# 格式化时间转时间戳
nextTime = time.mktime(ts)
return int(nextTime-nowTime)
def timeStrTime(strTime):
time_local = time.localtime(strTime)
#转换成新的时间格式(2018-05-26 20:20:20)
t = time.strftime("%H:%M:%S",time_local)
return t
def response_return(code, msg, data):
"""[summary]
Args:
code ([type]): 200(请求成功),404(请求失败),500(服务器出错)
msg ([type]): msg
data ([type]): json_data
Returns:
[type]: [description]
"""
if data == None:
data = []
return json.dumps({'code': code, 'msg': msg, 'data': list(data)}, ensure_ascii=False)
def GetImgNameByEveryDir(file_dir,videoProperty):
# Input Root Dir and get all img in per Dir.
# Out Every img with its filename and its dir and its path
FileNameWithPath = []
FileName = []
FileDir = []
for root, dirs, files in os.walk(file_dir):
for file in files:
if os.path.splitext(file)[1] in videoProperty:
FileNameWithPath.append(os.path.join(root, file)) # 保存图片路径
FileName.append(file) # 保存图片名称
FileDir.append(root[len(file_dir):]) # 保存图片所在文件夹
return FileName,FileNameWithPath,FileDir
def getNowFilePath():
"""[summary]
返回当前文件所在目录的绝对路径
Returns:
[string]: [当前文件所在目录的绝对路径]
"""
return os.path.split(os.path.abspath(__file__))[0]
def file_name(file_dir):
"""[summary]
返回所有子目录
Args:
file_dir ([type]): [description]
Returns:
[type]: [description]
"""
for root, dirs, files in os.walk(file_dir):
if dirs:
return dirs
def readConfig():
"""
读取config文件并返回
"""
# curpath = os.path.dirname(os.path.realpath(__file__))
cfgpath = os.path.join("./", "config.ini")
# 创建管理对象
conf = configparser.ConfigParser()
# 先读出来
conf.read(cfgpath, encoding="utf-8")
# 获取所有的section
sections = conf.sections()
allConfigDict={}
for i in sections:
items = conf.items(i)
for j in items:
allConfigDict[j[0]]=j[1]
return allConfigDict # list里面对象是元祖
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@文件 :dayData.py
@说明 :
@时间 :2021/09/22 11:44:32
@作者 :Cxk
@版本 :1.0
'''
import sqlite3
from utils import *
#-------------------------------Flow------------------------------------------------------------#
def openFlowData():
conn = sqlite3.connect("dayDate.db")
cur = conn.execute("""create table if not exists flowInfo(id integer PRIMARY KEY autoincrement,time varchar(30),todayInfo varchar(30),allInfo varchar(30))""")
return cur,conn
def insertFlowData(time,todayInfo,allInfo):
hel = openFlowData()
hel[1].execute("insert into flowInfo(time,todayInfo,allInfo) values (?,?,?)",(time,todayInfo,allInfo))
hel[1].commit()
hel[1].close()
def getBackFlowData():
try:
hel = openFlowData()
cur = hel[1].cursor()
cur.execute("select * from flowInfo order by id desc limit 1")
res = cur.fetchall()[0]
return res
except:
return (0, '2021-09-15 15:43:26', '0', '0')
#-------------------------------Error------------------------------------------------------------#
def openErrorData():
conn = sqlite3.connect("dayDate.db")
cur = conn.execute("""create table if not exists errorInfo(id integer PRIMARY KEY autoincrement,time varchar(30),errorInfo text)""")
return cur,conn
def insertErrorData(time,errorInfo):
hel = openErrorData()
hel[1].execute("insert into errorInfo(time,errorInfo) values (?,?)",(time,errorInfo))
hel[1].commit()
hel[1].close()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/7/10 14:02
# @Author : Cxk
# @File : main.py
import webbrowser
from PyQt5.QtCore import QSize, Qt, QPoint
from PyQt5.QtGui import QMouseEvent, QMovie, QCursor, QPalette
from PyQt5.QtWidgets import QWidget, QMessageBox, QApplication, QMenu, qApp, QColorDialog
# net_io_counters 网络输入与输出 如果需要获取单个网卡的io信息,加上pernic=True参数。
from psutil import net_io_counters
from threading import Thread
import threading
import os
import sys
import random,time
from qtpy import QtWidgets, QtCore
import pyautogui
import cv2
import numpy as np
def gsh(count):
if count < 1024:
return "%.2fB/s" % count
if count < 1048576:
return "%.2fKB/s" % (count / 1024)
count >>= 10
if count < 1048576:
return "%.2fMB/s" % (count / 1024)
count >>= 10
return "%.2fGB/s" % (count / 1024)
def get_data():
old = [0, 0]
new = [0, 0]
net_info = net_io_counters() # 获取流量统计信息
recv_bytes = net_info.bytes_recv
sent_bytes = net_info.bytes_sent
old[0] += recv_bytes
old[1] += sent_bytes
time.sleep(1)
# 当前所收集的数据
net_info = net_io_counters() # 获取流量统计信息
recv_bytes = net_info.bytes_recv
sent_bytes = net_info.bytes_sent
new[0] += recv_bytes
new[1] += sent_bytes
info = []
for i in range(2):
info.append(new[i] - old[i])
return info
class Main(QWidget):
_startPos = None
_endPos = None
_isTracking = False
all_bytes = 0
this_bytes = 0
about = "监控电脑网络的上传跟下载网速。\n统计网络使用总流量!\n作者:悟叭鸽"
txt_file = ""
rgb = (0, 255, 255)
size = 13
size_2 =360
addFlag = True
subFlag = False
def __init__(self):
try:
super().__init__()
self._initUI()
current_path = os.getcwd() # 获取当前路径
self.txt_file = current_path+os.sep+'流量使用情况.txt' # 在当前路径创建名为test的文本文件
if os.path.exists(self.txt_file):
with open(self.txt_file, 'r') as f:
self.all_bytes = int(f.read())
else:
with open(self.txt_file, 'a+') as f:
f.write(str(0))
with open(self.txt_file, 'r') as f:
self.all_bytes = int(f.read())
except Exception as e:
self.writeTxtThread()
QtWidgets.QMessageBox.critical(self, "错误", "系统错误\n%s" % e)
def _initUI(self):
try:
self.setFixedSize(QSize(1280, 720))
self.setWindowFlags(Qt.FramelessWindowHint |
QtCore.Qt.WindowStaysOnTopHint | Qt.Tool)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground) # 设置窗口背景透明
self.label = QtWidgets.QLabel(self)
self.label.resize(800, 600)
self.label.setGeometry(QtCore.QRect(0, 0, 1280, 720))
self.label.setMinimumSize(QtCore.QSize(290, 200))
self.label.setBaseSize(QtCore.QSize(290, 200))
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.label.setToolTip('按住左键移动\n点击右键菜单')
self.label.setStyleSheet(
"font: %s %spt \"Adobe Arabic\";color:rgb%s" %
(self.size_2, self.size, self.rgb))
self.timer = QtCore.QTimer(self)
self.timer.start(900)
self.timer.timeout.connect(self.start)
self.setCursor(QCursor(Qt.PointingHandCursor))
self.show()
except Exception as e:
self.writeTxtThread()
QtWidgets.QMessageBox.critical(self, "错误", "系统错误\n%s" % e)
def start(self):
try:
runThread = Thread(target=self.setSpeed, daemon=True, name="start")
runThread.start()
except Exception as e:
self.writeTxtThread()
QtWidgets.QMessageBox.critical(self, "错误", "系统错误\n%s" % e)
def writeTxtThread(self):
Thread(target=self.writeTxt, daemon=True).start()
def writeTxt(self):
with open(self.txt_file, 'w') as f:
f.write(str(self.all_bytes))
def aiSetColorThread(self):
Thread(target=self.aiSetColor, daemon=True).start()
def aiSetColor(self):
# 获取应用的下半部分进行截图提取颜色,对颜色进行高对比度再赋值
x,y = pyautogui.position() #返回鼠标的坐标
img = pyautogui.screenshot(region=[x-150,y+30,250,50]) # x,y,w,h
img = cv2.cvtColor(np.asarray(img),cv2.COLOR_RGB2BGR)
average_img = np.average(img, axis=0)
average_color = np.average(average_img, axis=0)
average_color = np.uint8(average_color)
# print(average_color)
c = average_color[2]-random.randint(0, 50)
b = average_color[1]^255
d = average_color[0]+random.randint(0, 50)
all_color = (c,b,d)
self.label.setStyleSheet(
"font: %s %spt \"Adobe Arabic\";color:rgb%s" % (self.size_2,self.size, all_color))
# cv2.imshow("winname", img)
# cv2.waitKey(0)
def setSpeed(self):
try:
info = get_data()
recv_bytes = gsh(info[0]) # 每秒接收的字节
sent_bytes = gsh(info[1]) # 每秒发送的字节
self.all_bytes += sum(info)
self.this_bytes += sum(info)
if self.all_bytes < 1073741824:
all_bytes = self.all_bytes / 1048576
strs = "❤%.2fMb❤" % all_bytes
else:
all_bytes = self.all_bytes / 1073741824
strs = "❤%.2fGb❤" % all_bytes
if self.this_bytes < 1073741824:
this_bytes = self.this_bytes / 1048576
strss = "❤%.2fMb❤" % this_bytes
else:
this_bytes = self.this_bytes / 1073741824
strss = "❤%.2fGb❤" % this_bytes
self.label.setText("⬆%s ⬇%s\n%s%s" %
(sent_bytes, recv_bytes, strss, strs))
except Exception as e:
self.writeTxtThread()
QtWidgets.QMessageBox.critical(self, "错误", "系统错误\n%s" % e)
def mouseMoveEvent(self, e: QMouseEvent): # 重写移动事件
try:
self._endPos = e.pos() - self._startPos
self.move(self.pos() + self._endPos)
except Exception as e:
self.writeTxtThread()
QtWidgets.QMessageBox.critical(self, "错误", "系统错误\n%s" % e)
def mousePressEvent(self, e: QMouseEvent):
try:
if e.button() == Qt.LeftButton:
self._isTracking = True
self._startPos = QPoint(e.x(), e.y())
if e.button() == Qt.RightButton:
menu = QMenu(self)
colorAction = menu.addAction("设置颜色")
sizeAction = menu.addAction("随机字体大小")
quitAction = menu.addAction("退出程序")
aboutAction = menu.addAction("关于程序")
action = menu.exec_(self.mapToGlobal(e.pos()))
if action == sizeAction:
if (self.size > 40):
self.size -= random.randint(0, 6)
self.subFlag = True
self.addFlag = False
if self.subFlag:
self.addFlag = False
self.size -= random.randint(0, 6)
if self.addFlag:
self.subFlag = False
self.size += random.randint(0, 6)
if self.size < 11:
self.addFlag = True
self.subFlag = False
self.size += random.randint(0, 6)
self.size_2 = random.randint(350, 1500)
self.label.setStyleSheet("font: %s %spt \"Adobe Arabic\";color:rgb%s" % (self.size_2,self.size, self.rgb))
# QtWidgets.QMessageBox.warning(self, "成功", "设置成功")
if action == colorAction:
color = QColorDialog.getColor()
self.rgb = color.getRgb()[:-1]
self.label.setStyleSheet("font: %s %spt \"Adobe Arabic\";color:rgb%s" % (self.size_2, self.size, self.rgb))
QtWidgets.QMessageBox.warning(self, "成功", "设置成功")
if action == quitAction:
self.writeTxtThread()
qApp.quit()
if action == aboutAction:
msg_box = QtWidgets.QMessageBox
msg_box.question(self, "关于", self.about,msg_box.Yes | msg_box.Cancel)
if QMessageBox.Yes:
webbrowser.open('https://me.csdn.net/Cxk___',
new=0, autoraise=True)
except Exception as e:
self.writeTxtThread()
QtWidgets.QMessageBox.critical(self, "错误", "系统错误\n%s" % e)
def mouseReleaseEvent(self, e: QMouseEvent):
try:
if e.button() == Qt.LeftButton:
self._isTracking = False
self._startPos = None
self._endPos = None
self.aiSetColorThread()
if e.button() == Qt.RightButton:
self._isTracking = False
self._startPos = None
self._endPos = None
except Exception as e:
self.writeTxtThread()
QtWidgets.QMessageBox.critical(self, "错误", "系统错误\n%s" % e)
app = QApplication(sys.argv)
ex = Main()
sys.exit(app.exec_())
开机自启动
点击该软件,然后鼠标右键菜单
创建快捷方式
接着
按住Win+r
输入:shell:startup
把快捷方式移入打开的文件夹