我找不到合适的实用程序来仅在面板上指示文件系统的使用情况(分区可用空间的百分比)。
我不希望安装任何不良的桌面管理工具,而是一个简单的指示器。
感谢您的所有建议。
我找不到合适的实用程序来仅在面板上指示文件系统的使用情况(分区可用空间的百分比)。
我不希望安装任何不良的桌面管理工具,而是一个简单的指示器。
感谢您的所有建议。
Answers:
尽管可以使用此答案底部的答案(请参阅参考资料[2.]
),但它会导致ppa
带有附加选项的-version,可以在首选项窗口中进行设置。
选项包括:
此外,指示器现在还为其他发行版(如xfce)设置了一个较小的(宽度)图标集,具体取决于窗口管理器,该图标将自动应用。
安装:
sudo add-apt-repository ppa:vlijm/spaceview
sudo apt-get update
sudo apt-get install spaceview
以下脚本是一个指示符,列出了您的设备并显示其使用情况。该信息每十秒钟更新一次(如有必要)。
此外
当指示器运行时,您可以选择要在图标中表示的设备。该设备将在您下次运行指示器时被记住:
对于一个或多个(或所有)设备,您可以设置一个备用名称(“自定义名称”),该名称将在脚本的开头进行设置
例如,这是:
alias = [
["sdc1", "stick"],
["sdb1", "External"],
["sda2", "root"],
["sda4", "ntfs1"],
["sda5", "ntfs2"],
["//192.168.0.104/media", "netwerk media"],
["//192.168.0.104/werkmap_documenten", "netwerk docs"],
]
将会呈现:
您可以设置一个阈值;如果其中任何一个设备的可用空间均低于该值,则会收到警告:
插入/未插入的设备将在10秒内从菜单列表中添加/删除。
#!/usr/bin/env python3
import subprocess
import os
import time
import signal
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk, AppIndicator3, GObject
from threading import Thread
#--- set alias names below in the format [[device1, alias1], [device2, alias2]]
#--- just set alias = [] to have no custom naming
alias = []
#--- set the threshold to show a warning below
#--- set to 0 to have no warning
threshold = 17
#---
currpath = os.path.dirname(os.path.realpath(__file__))
prefsfile = os.path.join(currpath, "showpreferred")
class ShowDevs():
def __init__(self):
self.default_dev = self.get_showfromfile()
self.app = 'show_dev'
iconpath = currpath+"/0.png"
self.indicator = AppIndicator3.Indicator.new(
self.app, iconpath,
AppIndicator3.IndicatorCategory.OTHER)
self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
self.indicator.set_menu(self.create_menu())
self.indicator.set_label("Starting up...", self.app)
self.update = Thread(target=self.check_changes)
self.update.setDaemon(True)
self.update.start()
def check_changes(self):
state1 = None
while True:
self.state2 = self.read_devices()
if self.state2 != state1:
self.update_interface(self.state2)
state1 = self.state2
time.sleep(10)
def update_interface(self, state):
warning = False; self.newmenu = []
for dev in state:
mention = self.create_mention(dev)
name = mention[0]; deci = mention[2]; n = mention[1]
if n <= threshold:
warning = True
try:
if self.default_dev in name:
newlabel = mention[3]
newicon = currpath+"/"+str(10-deci)+".png"
except TypeError:
pass
self.newmenu.append(name+" "+str(n)+"% free")
if warning:
newlabel = "Check your disks!"
newicon = currpath+"/10.png"
try:
self.update_indicator(newlabel, newicon)
except UnboundLocalError:
labeldata = self.create_mention(state[0])
newlabel = labeldata[3]
newicon = currpath+"/"+str(10-labeldata[2])+".png"
self.update_indicator(newlabel, newicon)
GObject.idle_add(self.set_new,
priority=GObject.PRIORITY_DEFAULT)
def update_indicator(self, newlabel, newicon):
GObject.idle_add(self.indicator.set_label,
newlabel, self.app,
priority=GObject.PRIORITY_DEFAULT)
GObject.idle_add(self.indicator.set_icon,
newicon,
priority=GObject.PRIORITY_DEFAULT)
def set_new(self):
for i in self.initmenu.get_children():
self.initmenu.remove(i)
for item in self.newmenu:
add = Gtk.MenuItem(item)
add.connect('activate', self.change_show)
self.initmenu.append(add)
menu_sep = Gtk.SeparatorMenuItem()
self.initmenu.append(menu_sep)
self.item_quit = Gtk.MenuItem('Quit')
self.item_quit.connect('activate', self.stop)
self.initmenu.append(self.item_quit)
self.initmenu.show_all()
def change_show(self, *args):
index = self.initmenu.get_children().index(self.initmenu.get_active())
self.default_dev = self.newmenu[index].split()[0]
open(prefsfile, "wt").write(self.default_dev)
self.update_interface(self.read_devices())
def create_mention(self, dev):
name = dev[1] if dev[1] else dev[0]
n = dev[2]; deci = round(dev[2]/10)
newlabel = name+" "+str(n)+"% free"
return (name, n, deci, newlabel)
def create_menu(self):
# create initial basic menu
self.initmenu = Gtk.Menu()
self.item_quit = Gtk.MenuItem('Quit')
self.item_quit.connect('activate', self.stop)
self.initmenu.append(self.item_quit)
self.initmenu.show_all()
return self.initmenu
def read_devices(self):
# read the devices, look up their alias and the free sapace
devdata = []
data = subprocess.check_output(["df", "-h"]).decode("utf-8").splitlines()
relevant = [l for l in data if all([
any([l.startswith("/dev/"), l.startswith("//")]),
not "/loop" in l])
]
for dev in relevant:
data = dev.split(); name = data[0]; pseudo = None
free = 100-int([s.strip("%") for s in data if "%" in s][0])
for al in alias:
if al[0] in name:
pseudo = al[1]
break
devdata.append((name, pseudo, free))
return devdata
def get_showfromfile(self):
# read the preferred default device from file
try:
defdev = open(prefsfile).read().strip()
except FileNotFoundError:
defdev = None
return defdev
def stop(self, source):
Gtk.main_quit()
ShowDevs()
GObject.threads_init()
signal.signal(signal.SIGINT, signal.SIG_DFL)
Gtk.main()
设置很简单:
showusage.py
在脚本的开头部分,设置(可能)备用名称(aliasses
)。下面是一个例子:
alias = [
["sda2", "root"],
["sdb1", "External"]
]
如果要不更改显示设备,请使用:
alias = []
...,然后根据需要更改阈值以显示警告:
#--- set the threshold to show a warning below (% free, in steps of 10%)
#--- set to 0 to have no warning
threshold = 10
而已
要使用指示器,请运行以下命令:
python3 /path/to/showusage.py
要将其添加到启动应用程序,请使用以下命令:
/bin/bash -c "sleep 10 && python3 /path/to/showusage.py"
选择“应用程序:破折号>启动应用程序>添加”,添加上面的命令。
免责声明:我是该指标的作者,它是针对这个特定问题而撰写的
该指标现在支持 列出网络共享。感谢mihaigalos
指示器现在具有卸载功能,并且通过引用每个分区的UUID而不是块设备名称(例如)来使别名唯一sda1
。查看相关的错误报告
该指标现在是2.0版,增加了一些功能并拥有自己的PPA。
要从PPA安装,请在终端中使用以下步骤:
sudo apt-add-repository ppa:udisks-indicator-team/ppa
sudo bash -c 'apt-get update && apt-get install udisks-indicator'
如发行说明中所述,这些功能包括:
Ubuntu Kylin图标主题
关闭所有可选字段
在制定此指标时,我希望获得一种适用于高级和休闲用户的实用程序。我试图解决一些新用户在处理命令行工具时可能遇到的问题。另外,该实用程序努力成为多用途的。
使用“首选项”对话框可以使指示器复杂和/或简单,如用户所愿。这也是一个特定的设计决策,要避免在顶部面板中贴标签,以免占用用户的顶部面板空间过多。另外,该指示器致力于成为一种多功能工具,该工具允许安装分区以及打开其各自的目录。它不仅可以用作磁盘使用实用程序,还可以用作导航实用程序以快速打开目录。
用户也很方便地知道哪个分区驻留在哪个磁盘上,从而避免了通过诸如的命令行实用程序进行安装时的频繁混淆mount
。相反,它udisksctl
为此目的而使用(以及从UDisks2
守护程序中获取信息,从而进行命名)。它唯一不执行的任务是卸载,或者因此包含Open Disks Utility
菜单项。
虽然最初我努力使其类似于iStat menulet,但该项目与该目标有所不同-该指示器在设计和目的上都是独一无二的。我希望它将对许多用户有用,并使他们的Ubuntu体验更加愉快。
带有Unity的Ubuntu指示器可轻松查看有关已安装分区的信息。它努力在视觉上类似于OS X中的iStat Menu 3菜单。
条目按顺序组织:
单击每个分区条目将在默认文件管理器中打开分区的挂载点
“未安装的分区”菜单列出了系统当前未安装的所有分区。单击该子菜单中的任何条目将自动将该分区安装,通常安装到/media/username/drive-id
文件夹
该指示器使用系统随附的默认图标,因此当您使用Unity Tweak Tool或其他方法更改图标主题时,该图标应在更改
注意:如果要同时添加多个别名,而不是通过“ Make Alias”选项一个接一个地添加,可以通过编辑~/.partition_aliases.json
配置文件来添加。格式如下:
{
"sda1": "Alias 1",
"sda2": "Alias 2",
"sdb1": "Alias 3"
}
易于安装的PPA即将推出。。。
同时,这是替代步骤:
cd /tmp
wget https://github.com/SergKolo/udisks-indicator/archive/master.zip
unzip master.zip
sudo install udisks-indicator-master/udisks-indicator /usr/bin/udisks-indicator
sudo install udisks-indicator-master/udisks-indicator.desktop /usr/share/applications/udisks-indicator.desktop
所有这些步骤都可以放入一个不错的安装脚本中:
#!/bin/bash
cd /tmp
rm master.zip*
wget https://github.com/SergKolo/udisks-indicator/archive/master.zip
unzip master.zip
install udisks-indicator-master/udisks-indicator /usr/bin/udisks-indicator
install udisks-indicator-master/udisks-indicator.desktop /usr/share/applications/udisks-indicator.desktop
具有此指示器基本功能的原始源代码(版本v1.0)可在下面找到。有关最新功能,请检查此项目的GitHub存储库。请报告任何功能请求以及GitHub上的错误。
的/usr/bin/udisks-indicator
:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Author: Serg Kolo , contact: 1047481448@qq.com
# Date: September 27 , 2016
# Purpose: appindicator for displaying mounted filesystem usage
# Tested on: Ubuntu 16.04 LTS
#
#
# Licensed under The MIT License (MIT).
# See included LICENSE file or the notice below.
#
# Copyright © 2016 Sergiy Kolodyazhnyy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import gi
gi.require_version('AppIndicator3', '0.1')
from gi.repository import GLib as glib
from gi.repository import AppIndicator3 as appindicator
from gi.repository import Gtk as gtk
from os import statvfs
#from collections import OrderedDict
import subprocess
import shutil
import dbus
import json
import os
class UdisksIndicator(object):
def __init__(self):
self.app = appindicator.Indicator.new(
'udisks-indicator', "drive-harddisk-symbolic.svg",
appindicator.IndicatorCategory.HARDWARE
)
if not self.app.get_icon():
self.app.set_icon("drive-harddisk-symbolic")
self.app.set_status(appindicator.IndicatorStatus.ACTIVE)
filename = '.partition_aliases.json'
user_home = os.path.expanduser('~')
self.config_file = os.path.join(user_home,filename)
self.cache = self.get_partitions()
self.make_menu()
self.update()
def update(self):
timeout = 5
glib.timeout_add_seconds(timeout,self.callback)
def callback(self):
if self.cache != self.get_partitions():
self.make_menu()
self.update()
def make_menu(self,*args):
""" generates entries in the indicator"""
if hasattr(self, 'app_menu'):
for item in self.app_menu.get_children():
self.app_menu.remove(item)
self.app_menu = gtk.Menu()
partitions = self.get_partitions()
for i in partitions:
part = "Partition: " + i[0]
alias = self.find_alias(i[0])
drive = "\nDrive: " + i[1]
mount = "\nMountPoint: " + i[2]
usage = "\n%Usage: " + i[3]
item = part + drive + mount + usage
if alias:
alias = "\nAlias: " + alias
item = part + alias + drive + mount + usage
self.menu_item = gtk.MenuItem(item)
self.menu_item.connect('activate',self.open_mountpoint,i[2])
self.app_menu.append(self.menu_item)
self.menu_item.show()
self.separator = gtk.SeparatorMenuItem()
self.app_menu.append(self.separator)
self.separator.show()
self.unmounted = gtk.MenuItem('Unmounted Partitions')
self.unmounted_submenu = gtk.Menu()
self.unmounted.set_submenu(self.unmounted_submenu)
for i in self.get_unmounted_partitions():
# TODO: add type checking, prevent swap
part = "Partition: " + i[0]
alias = self.find_alias(i[0])
drive = "\nDrive: " + i[1]
label = part + drive
if alias:
alias = "\nAlias: " + alias
label = part + alias + drive
self.menu_item = gtk.MenuItem(label)
self.menu_item.connect('activate',self.mount_partition,i[0])
self.unmounted_submenu.append(self.menu_item)
self.menu_item.show()
self.separator = gtk.SeparatorMenuItem()
self.unmounted_submenu.append(self.separator)
self.separator.show()
self.app_menu.append(self.unmounted)
self.unmounted.show()
self.separator = gtk.SeparatorMenuItem()
self.app_menu.append(self.separator)
self.separator.show()
self.make_part_alias = gtk.MenuItem('Make Alias')
self.make_part_alias.connect('activate',self.make_alias)
self.app_menu.append(self.make_part_alias)
self.make_part_alias.show()
user_home = os.path.expanduser('~')
desktop_file = '.config/autostart/udisks-indicator.desktop'
full_path = os.path.join(user_home,desktop_file)
label = 'Start Automatically'
if os.path.exists(full_path):
label = label + ' \u2714'
self.autostart = gtk.MenuItem(label)
self.autostart.connect('activate',self.toggle_auto_startup)
self.app_menu.append(self.autostart)
self.autostart.show()
self.open_gnome_disks = gtk.MenuItem('Open Disks Utility')
self.open_gnome_disks.connect('activate',self.open_disks_utility)
self.app_menu.append(self.open_gnome_disks)
self.open_gnome_disks.show()
self.quit_app = gtk.MenuItem('Quit')
self.quit_app.connect('activate', self.quit)
self.app_menu.append(self.quit_app)
self.quit_app.show()
self.app.set_menu(self.app_menu)
def mount_partition(self,*args):
# TODO: implement error checking for mounting
return self.run_cmd(['udisksctl','mount','-b','/dev/' + args[-1]])
def get_mountpoint_usage(self,mountpoint):
fs = statvfs(mountpoint)
usage = 100*(float(fs.f_blocks)-float(fs.f_bfree))/float(fs.f_blocks)
return str("{0:.2f}".format(usage))
def get_partitions(self):
objects = self.get_dbus('system',
'org.freedesktop.UDisks2',
'/org/freedesktop/UDisks2',
'org.freedesktop.DBus.ObjectManager',
'GetManagedObjects',
None)
partitions = []
for item in objects:
try:
if 'block_devices' in str(item):
drive = self.get_dbus_property('system',
'org.freedesktop.UDisks2',
item,
'org.freedesktop.UDisks2.Block',
'Drive')
if drive == '/': continue
mountpoint = self.get_mountpoint(item)
if not mountpoint: continue
mountpoint = mountpoint.replace('\x00','')
drive = str(drive).split('/')[-1]
usage = self.get_mountpoint_usage(mountpoint)
part = str(item.split('/')[-1])
partitions.append((part,drive,mountpoint,usage))
except Exception as e:
#print(e)
pass
# returning list of tuples
partitions.sort()
return partitions
def get_mountpoint(self,dev_path):
try:
data = self.get_dbus_property(
'system',
'org.freedesktop.UDisks2',
dev_path,
'org.freedesktop.UDisks2.Filesystem',
'MountPoints')[0]
except Exception as e:
#print(e)
return None
else:
if len(data) > 0:
return ''.join([ chr(byte) for byte in data])
def get_unmounted_partitions(self):
objects = self.get_dbus('system',
'org.freedesktop.UDisks2',
'/org/freedesktop/UDisks2',
'org.freedesktop.DBus.ObjectManager',
'GetManagedObjects',
None)
partitions = []
for item in objects:
try:
if 'block_devices' in str(item):
drive = self.get_dbus_property('system',
'org.freedesktop.UDisks2',
item,
'org.freedesktop.UDisks2.Block',
'Drive')
if drive == '/': continue
mountpoint = self.get_mountpoint(item)
if mountpoint: continue
drive = str(drive).split('/')[-1]
part = str(item.split('/')[-1])
if not part[-1].isdigit(): continue
partitions.append((part,drive))
#print(partitions)
except Exception as e:
#print(e)
pass
partitions.sort()
return partitions
def get_dbus(self,bus_type,obj,path,interface,method,arg):
if bus_type == "session":
bus = dbus.SessionBus()
if bus_type == "system":
bus = dbus.SystemBus()
proxy = bus.get_object(obj,path)
method = proxy.get_dbus_method(method,interface)
if arg:
return method(arg)
else:
return method()
def get_dbus_property(self,bus_type,obj,path,iface,prop):
if bus_type == "session":
bus = dbus.SessionBus()
if bus_type == "system":
bus = dbus.SystemBus()
proxy = bus.get_object(obj,path)
aux = 'org.freedesktop.DBus.Properties'
props_iface = dbus.Interface(proxy,aux)
props = props_iface.Get(iface,prop)
return props
def make_alias(self,*args):
partitions = [ i[0] for i in self.get_partitions() ]
combo_values = '|'.join(partitions)
#print(combo_values)
command=[ 'zenity','--forms','--title','Make Alias',
'--add-combo','Partition','--combo-values',
combo_values,'--add-entry','Alias' ]
user_input = self.run_cmd(command)
if not user_input: return
alias = user_input.decode().strip().split('|')
existing_values = None
if os.path.isfile(self.config_file):
with open(self.config_file) as conf_file:
try:
existing_values = json.load(conf_file)
except ValueError:
pass
with open(self.config_file,'w') as conf_file:
if existing_values:
existing_values[alias[0]] = alias[1]
else:
existing_values = {alias[0]:alias[1]}
#print(existing_values)
json.dump(existing_values,conf_file,indent=4,sort_keys=True)
def find_alias(self,part):
if os.path.isfile(self.config_file):
with open(self.config_file) as conf_file:
try:
aliases = json.load(conf_file)
except ValueError:
pass
else:
if part in aliases:
return aliases[part]
else:
return None
def toggle_auto_startup(self,*args):
user_home = os.path.expanduser('~')
desktop_file = '.config/autostart/udisks-indicator.desktop'
full_path = os.path.join(user_home,desktop_file)
if os.path.exists(full_path):
os.unlink(full_path)
else:
original = '/usr/share/applications/udisks-indicator.desktop'
if os.path.exists(original):
shutil.copyfile(original,full_path)
self.make_menu()
def open_mountpoint(self,*args):
pid = subprocess.Popen(['xdg-open',args[-1]]).pid
def open_disks_utility(self,*args):
pid = subprocess.Popen(['gnome-disks']).pid
def run_cmd(self, cmdlist):
""" Reusable function for running external commands """
new_env = dict(os.environ)
new_env['LC_ALL'] = 'C'
try:
stdout = subprocess.check_output(cmdlist, env=new_env)
except subprocess.CalledProcessError:
pass
else:
if stdout:
return stdout
def run(self):
""" Launches the indicator """
try:
gtk.main()
except KeyboardInterrupt:
pass
def quit(self, data=None):
""" closes indicator """
gtk.main_quit()
def main():
""" defines program entry point """
indicator = UdisksIndicator()
indicator.run()
if __name__ == '__main__':
main()
的 /usr/share/applications/udisks-indicator.desktop
[Desktop Entry]
Version=1.0
Name=Udisks Indicator
Comment=Indicator for reporting partition information
Exec=udisks-indicator
Type=Application
Icon=drive-harddisk-symbolic.svg
Terminal=false
Ubuntu Mate 16.04测试:
侏儒用户需要扩展(KStatusNotifierItem / AppIndicator支持)以使指标正常运行:
sudo add-apt-repository ppa:fossfreedom/indicator-sysmonitor
sudo apt-get update
sudo apt-get install indicator-sysmonitor
并且具有“文件系统中的可用空间”选项。
使用基本的Sysmonitor指示器还有另一个答案但是您可以根据需要创建自己的自定义面板,其中包含尽可能多的信息。
第一步是弄清楚如何计算分区使用率:
$ percentage=($(df -k --output=pcent /dev/sda1))
$ echo "${percentage[1]}"
13%
这是一个bash脚本,用作Sysmonitor Indicator中的 “自定义”选项。它将显示前三个分区上使用的百分比/dev/sda
:
#!/bin/bash
echo "sda1: "
percentage=($(df -k --output=pcent /dev/sda1))
echo "${percentage[1]}"
echo " | sda2: "
percentage=($(df -k --output=pcent /dev/sda2))
echo "${percentage[1]}"
echo " | sda3: "
percentage=($(df -k --output=pcent /dev/sda3))
echo "${percentage[1]}"
运行时将如下所示:
有关安装Sysmonitor Indicator和分配自定义脚本的详细说明,请参见以下答案:BASH能否在Systray中显示为应用程序指示符?
/dev/sdb1
并在其旁边使用它?以百分比还是实际的千兆字节为单位?