有一个应用程序使用时间跟踪器脚本,雅各布·弗莱姆在另一个问题中写道。https://askubuntu.com/a/780542/654800
由于名气小,我无法在那里发表评论。所以我想在这里问一下,是否可以按使用百分比而不是当前相对顺序对条目进行排序?
如果您不想检查原始问题,这里有一个脚本。
#!/usr/bin/env python3
import subprocess
import time
import os
# -- set update/round time (seconds)
period = 5
# --
# don change anything below
home = os.environ["HOME"]
logdir = home+"/.usagelogs"
def currtime(tformat=None):
return time.strftime("%Y_%m_%d_%H_%M_%S") if tformat == "file"\
else time.strftime("%Y-%m-%d %H:%M:%S")
try:
os.mkdir(logdir)
except FileExistsError:
pass
# path to your logfile
log = logdir+"/"+currtime("file")+".txt"; startt = currtime()
def get(command):
try:
return subprocess.check_output(command).decode("utf-8").strip()
except subprocess.CalledProcessError:
pass
def time_format(s):
# convert time format from seconds to h:m:s
m, s = divmod(s, 60); h, m = divmod(m, 60)
return "%d:%02d:%02d" % (h, m, s)
def summarize():
with open(log, "wt" ) as report:
totaltime = sum([it[2] for it in winlist])
report.write("")
for app in applist:
wins = [r for r in winlist if r[0] == app]
apptime = sum([it[2] for it in winlist if it[0] == app])
appperc = round(100*apptime/totaltime)
report.write(("-"*60)+"\n"+app+"\n"+time_format(apptime)+\
" ("+str(appperc)+"%)\n"+("-"*60)+"\n")
for w in wins:
wperc = str(round(100*w[2]/totaltime))
report.write(" "+time_format(w[2])+" ("+\
wperc+"%)"+(6-len(wperc))*" "+w[1]+"\n")
report.write("\n"+"="*60+"\nstarted: "+startt+"\t"+\
"updated: "+currtime()+"\n"+"="*60)
t = 0; applist = []; winlist = []
while True:
time.sleep(period)
frpid = get(["xdotool", "getactivewindow", "getwindowpid"])
frname = get(["xdotool", "getactivewindow", "getwindowname"])
app = get(["ps", "-p", frpid, "-o", "comm="]) if frpid != None else "Unknown"
# fix a few names
if "gnome-terminal" in app:
app = "gnome-terminal"
elif app == "soffice.bin":
app = "libreoffice"
# add app to list
if not app in applist:
applist.append(app)
checklist = [item[1] for item in winlist]
if not frname in checklist:
winlist.append([app, frname, 1*period])
else:
winlist[checklist.index(frname)][
2] = winlist[checklist.index(frname)][2]+1*period
if t == 60/period:
summarize()
t = 0
else:
t += 1
答案1
剧本相同,但制作已排序报告,升序或降序
我编辑了脚本以生成排序的报告(升序或降序),并将其设置在脚本的头部。
排序是按照应用程序以及他们的视窗(在每个应用程序的子列表中)。
剧本
#!/usr/bin/env python3
import subprocess
import time
import os
from operator import itemgetter
# -- set update/round time (seconds)
period = 5
# -- set sorting order. up = most used first, use either "up" or "down"
order = "up"
# don change anything below
home = os.environ["HOME"]
logdir = home+"/.usagelogs"
def currtime(tformat=None):
return time.strftime("%Y_%m_%d_%H_%M_%S") if tformat == "file"\
else time.strftime("%Y-%m-%d %H:%M:%S")
try:
os.mkdir(logdir)
except FileExistsError:
pass
# path to your logfile
log = logdir+"/"+currtime("file")+".txt"; startt = currtime()
def get(command):
try:
return subprocess.check_output(command).decode("utf-8").strip()
except subprocess.CalledProcessError:
pass
def time_format(s):
# convert time format from seconds to h:m:s
m, s = divmod(s, 60); h, m = divmod(m, 60)
return "%d:%02d:%02d" % (h, m, s)
def summarize():
with open(log, "wt" ) as report:
totaltime = sum([it[2] for it in winlist]) # total time
report.write("")
alldata = []
for app in applist:
appdata = []; windata = []
apptime = sum([it[2] for it in winlist if it[0] == app])
appperc = round(100*apptime/totaltime)
for d in [app, apptime, appperc]:
appdata.append(d)
wins = [r for r in winlist if r[0] == app]
for w in wins:
wperc = str(round(100*w[2]/totaltime))
windata.append([w[1], w[2], wperc])
windata = sorted(windata, key=itemgetter(1))
windata = windata[::-1] if order == "up" else windata
appdata.append(windata); alldata.append(appdata)
alldata = sorted(alldata, key = itemgetter(1))
alldata = alldata[::-1] if order == "up" else alldata
for item in alldata:
app = item[0]; apptime = item[1]; appperc = item[2]
report.write(
("-"*60)+"\n"+app+"\n"+time_format(apptime)\
+" ("+str(appperc)+"%)\n"+("-"*60)+"\n"
)
for w in item[3]:
wname = w[0]; time = w[1]; perc = w[2]
report.write(
" "+time_format(time)+" ("+perc+"%)"\
+(6-len(perc))*" "+wname+"\n"
)
report.write(
"\n"+"="*60+"\nstarted: "+startt+"\t"+"updated: "\
+currtime()+"\n"+"="*60
)
t = 0; applist = []; winlist = []
while True:
time.sleep(period)
frpid = get(["xdotool", "getactivewindow", "getwindowpid"])
frname = get(["xdotool", "getactivewindow", "getwindowname"])
app = get([
"ps", "-p", frpid, "-o", "comm="
]) if frpid != None else "Unknown"
# fix a few names
if "gnome-terminal" in app:
app = "gnome-terminal"
elif app == "soffice.bin":
app = "libreoffice"
# add app to list
if not app in applist:
applist.append(app)
checklist = [item[1] for item in winlist]
if not frname in checklist:
winlist.append([app, frname, 1*period])
else:
winlist[checklist.index(frname)][
2] = winlist[checklist.index(frname)][2]+1*period
if t == 60/period:
summarize()
t = 0
else:
t += 1
它产生如下输出:
------------------------------------------------------------
firefox
0:08:25 (97%)
------------------------------------------------------------
0:06:50 (79%) Sort by percentage of use in a python script - Ask Ubuntu - Mozilla Firefox
0:01:30 (17%) scripts - Is there software which time- tracks window & application usage? - Ask Ubuntu - Mozilla Firefox
0:00:05 (1%) Ask Ubuntu General Room | chat.stackexchange.com - Mozilla Firefox
------------------------------------------------------------
gedit
0:00:10 (2%)
------------------------------------------------------------
0:00:10 (2%) 2017_02_15_20_47_10.txt (~/.usagelogs) - gedit
------------------------------------------------------------
zenity
0:00:05 (1%)
------------------------------------------------------------
0:00:05 (1%) Paste snippets
============================================================
started: 2017-02-15 20:58:19 updated: 2017-02-15 21:07:03
============================================================
使用
脚本需要
xdotool
获取窗口的信息sudo apt-get install xdotool
将脚本复制到一个空文件中,另存为
window_logs.py
测试运行脚本:通过命令启动脚本(从终端):
python3 /path/to/window_logs.py
一分钟后,脚本会创建一个日志文件,其中包含第一批结果
~/.usagelogs
。该文件带有创建日期和时间的时间戳。该文件每分钟更新一次。在文件底部,您可以看到最新编辑的开始时间和时间戳。这样,您就可以随时看到文件的时间跨度。
如果脚本重新启动,则会创建一个具有新(开始)时间戳的新文件。
如果一切正常,请添加到启动应用程序:Dash > 启动应用程序 > 添加。添加命令:
/bin/bash -c "sleep 15 && python3 /path/to/window_logs.py"
逆序排列
要反转排序顺序,只需更改脚本头部的参数:
# -- set sorting order. up = most used first, use either "up" or "down"
order = "up"
注意:请阅读笔记和更多笔记部分链接答案!