Created
July 2, 2013 13:19
-
-
Save agateau/5909244 to your computer and use it in GitHub Desktop.
Quick script to set labels of vfat volumes. Useful to name usb sticks.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os | |
import re | |
import signal | |
import subprocess | |
import sys | |
from PyQt4.QtCore import * | |
from PyQt4.QtGui import * | |
class MtoolsError(Exception): | |
def __init__(self, cmd, output): | |
self.cmd = cmd | |
self.output = output | |
def __str__(self): | |
return "command: {}\noutput: {}".format(self.cmd, self.output) | |
def failure(msg): | |
QMessageBox.critical(None, qApp.tr("Error"), msg, QMessageBox.Close) | |
def getLabel(device): | |
out_prefix1 = re.compile("^ Volume label is (.+[^ ]) +\(.*\)$") | |
out_prefix2 = re.compile("^ Volume label is (.+[^ ]) +$") | |
cmd = ["mlabel", "-i", device, "-s", "::"] | |
print("Running {}".format(cmd)) | |
try: | |
out = subprocess.check_output(cmd, stderr=subprocess.STDOUT) | |
except subprocess.CalledProcessError, exc: | |
raise MtoolsError(cmd, exc.output) | |
print("Output: {}".format(out)) | |
match = out_prefix1.match(out) | |
if match: | |
return match.group(1) | |
match = out_prefix2.match(out) | |
if match: | |
return match.group(1) | |
if out.strip() == "Volume has no label": | |
return "" | |
raise Exception("Unexpected out from mlabel: {}".format(out)) | |
def setLabel(device, label): | |
cmd = ["mlabel", "-i", device, "::" + label] | |
print("Running {}".format(cmd)) | |
return subprocess.call(cmd, stderr=subprocess.STDOUT) | |
def main(): | |
signal.signal(signal.SIGINT, signal.SIG_DFL) | |
app = QApplication(sys.argv) | |
if len(sys.argv) != 2: | |
failure("Usage: <tt>labelstick </dev/path></tt>") | |
return 1 | |
if os.getuid() != 0: | |
return os.execlp("kdesudo", "python", *sys.argv) | |
device = sys.argv[1] | |
try: | |
label = getLabel(device) | |
except MtoolsError, exc: | |
failure( | |
app.tr("<p>Labelstick failed to read label for partition <tt>%1</tt>.</p>" | |
"<p>Make sure the partition name is correct and is a VFAT partition.</p>" | |
"<p>Detailed error:</p><pre>%2</pre>" | |
).arg(device).arg(str(exc)) | |
) | |
return 1 | |
newLabel, ok = QInputDialog.getText(None, app.tr("Label partition %1").arg(device), | |
app.tr("Please enter a label for partition (11 characters maximum):"), | |
QLineEdit.Normal, | |
label) | |
if not ok: | |
return 0 | |
newLabel = newLabel[:11] | |
if label != newLabel: | |
try: | |
setLabel(device, newLabel) | |
except subprocess.CalledProcessError: | |
failure("Failed to set label.") | |
return 0 | |
if __name__ == "__main__": | |
sys.exit(main()) | |
# vi: ts=4 sw=4 et |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment