Add natural sort for output
For all items of table display, they will now use a natural sort, so it
more user friendly. This added two functions for finding and converting
numbers in an item name, in the first column of a table. These numbers
are then used to help with ordering the total list.
Signed-off-by: Justin Thaler thalerj@us.ibm.com
diff --git a/thalerj/openbmctool.py b/thalerj/openbmctool.py
index 3f64127..9af4a7f 100644
--- a/thalerj/openbmctool.py
+++ b/thalerj/openbmctool.py
@@ -28,6 +28,7 @@
import tarfile
import tempfile
import hashlib
+import re
def hilight(textToColor, color, bold):
"""
@@ -176,7 +177,29 @@
else:
return "No"
+def stringToInt(text):
+ """
+ returns an integer if the string can be converted, otherwise returns the string
+
+ @param text: the string to try to convert to an integer
+ """
+ if text.isdigit():
+ return int(text)
+ else:
+ return text
+def naturalSort(text):
+ """
+ provides a way to naturally sort a list
+
+ @param text: the key to convert for sorting
+ @return list containing the broken up string parts by integers and strings
+ """
+ stringPartList = []
+ for c in re.split('(\d+)', text):
+ stringPartList.append(stringToInt(c))
+ return stringPartList
+
def tableDisplay(keylist, colNames, output):
"""
Logs into the BMC and creates a session
@@ -193,8 +216,10 @@
if (i != 0): row = row + "| "
row = row + colNames[i].ljust(colWidth[i])
outputText += row + "\n"
-
- for key in sorted(output.keys()):
+
+ output_keys = list(output.keys())
+ output_keys.sort(key=naturalSort)
+ for key in output_keys:
row = ""
for i in range(len(output[key])):
if (i != 0): row = row + "| "