我无法找到合适的实用程序来在面板上指示文件系统使用情况(分区可用空间的百分比)。
而且我并不希望安装任何糟糕的桌面管理工具,而只是一个简单的指示器。
我感谢您的所有建议。
答案1
编辑:
1. 新答案
虽然可以使用该答案底部的答案(参见[2.]
),但它会导致出现ppa
带有附加选项的版本,可在首选项窗口中设置。
选项包括:
此外,指示器现在包括为其他发行版(如 xfce)设置的较小(宽度)图标,该图标将根据窗口管理器自动应用。
安装:
sudo add-apt-repository ppa:vlijm/spaceview
sudo apt-get update
sudo apt-get install spaceview
2. 旧答案
以下脚本是一个指示器,列出您的设备并显示其使用情况。信息每十秒更新一次(如有必要)。
此外
指标运行时,您可以选择一个设备以图标表示。下次运行指标时,将记住该设备:
对于一个或多个(或所有)设备,您可以设置备用名称(“自定义名称”),该名称应设置在脚本的开头
例如:
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"
选择应用程序:Dash > 启动应用程序 > 添加,添加上述命令。
答案2
免责声明:我是这个指标的作者,它是针对这个特定问题编写的
更新日期:2018年10月23日
2016 年 10 月 29 日更新
指示器现在具有卸载功能,并且通过引用每个分区的 UUID 而不是块设备名称(例如)使别名变得唯一sda1
。请参阅相关错误报告
更新,2016年10月8日
该指标目前为 2.0 版本,增加了一些功能并拥有自己的 PPA。
要从 PPA 安装,请在终端中执行以下步骤:
sudo apt-add-repository ppa:udisks-indicator-team/ppa
sudo bash -c 'apt-get update && apt-get install udisks-indicator'
正如在发行说明其特点包括:
- 菜单项的图标:每个分区/设备都附有相应的图标。如果设备是 USB 磁盘,则使用可移动媒体图标;如果是 ISO 映像,则使用光盘图标;显然,硬盘驱动器/SSD 分区有驱动器图标。
- 使用情况现在以百分比和人类可读的值( 1024 的幂)显示。
- 通过使用栏以图形方式表示使用情况(非常感谢 Mateo Salta 的想法)
- 首选项对话框:用户可以关闭每个菜单项中他们不想看到的某些字段。如果连接了大量分区,这可以保持指示器菜单整洁。(感谢 Zacharee 的请求)
- 文本间距:使用默认的 Ubuntu 字体和等宽字体,文本条目间距适当,外观更清晰,信息可读性增强。
- 分区无法安装时出现通知气泡
Ubuntu Kylin 图标主题
关闭所有可选字段
设计选择和其他想法:
在制作此指标时,我希望实现一款适合高级用户和普通用户的实用程序。我尝试解决我注意到的新用户在使用命令行工具时可能遇到的一些问题。此外,该实用程序力求实现多用途。
首选项对话框允许根据用户的需要将指示器设置得尽可能复杂和/或简单。避免在顶部面板上放置标签也是一项特殊的设计决定,这样它就不会占用太多用户的顶部面板空间。此外,该指示器力求成为多用途实用程序,允许安装分区以及打开其各自的目录。它不仅可以用作磁盘使用实用程序,还可以用作快速打开目录的导航实用程序。
用户还可以方便地知道哪个分区位于哪个磁盘上,从而避免经常与通过命令行实用程序(如)进行安装混淆mount
。相反,它为此目的使用udisksctl
(以及从UDisks2
守护程序获取信息,因此命名)。它不执行的唯一任务是卸载,因此Open Disks Utility
包含菜单项。
虽然我最初努力使它类似于 iStat menulet,但该项目偏离了这个目标——该指示器在设计和用途上是独一无二的。我希望它对许多用户有用,并使他们的 Ubuntu 体验更加愉快。
udisks-indicator (原始答案)
带有 Unity 桌面的 Ubuntu 指示器显示磁盘使用情况
概述
此 Ubuntu Unity 指示器可让您轻松查看已安装分区的信息。它力求在视觉上与 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: [email protected]
# 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测试:
Gnome 用户需要一个扩展(KStatusNotifierItem/AppIndicator 支持)才能使指示器正常运行:
答案3
sudo add-apt-repository ppa:fossfreedom/indicator-sysmonitor
sudo apt-get update
sudo apt-get install indicator-sysmonitor
并且它有“文件系统中的可用空间”选项。
答案4
还有另一个答案使用基本的Sysmonitor 指标但您可以创建自己的自定义面板,并根据需要提供尽可能多的信息。
Google(至少在搜索方面)是你的朋友
第一步是弄清楚如何计算分区使用百分比:
$ percentage=($(df -k --output=pcent /dev/sda1))
$ echo "${percentage[1]}"
13%
创建 bash 脚本来回显到面板
这是一个用作“自定义”选项的 bash 脚本Sysmonitor 指标。它将显示前三个分区使用的百分比/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 中安装和配置自定义脚本
有关安装的详细说明Sysmonitor 指标并分配自定义脚本请参见以下答案:BASH 可以作为应用程序指示器显示在系统托盘中吗?