I have a simple problem that seems to have numerous solutions, so I was curious how you would solve this problem. I'm almost embarrassed to ask, but I'd love to hear different approaches.
I have a script that parses out a serial number of a connected USB device. If you're at all familiar with android automation, you might be familiar with the "adb" command. it lists the serial numbers of connected devices. I'm intentionally limiting the script to only work when 1 device is connected. I've implemented a solution that is not robust, that's for sure. But I'm wondering how you would write it differently, SPECIFICALLY the parsing section. I'm using python, btw. The copy/paste job appears to remove the indentations though.
Here's what's written to stdout when you issue the "adb devices" command:
List of devices attached
V0124355SN device
<this is a blank line!>
How would you parse out that serial number? Here's what I'm doing. All critiques welcome.
def get_dsn():
cmd = ["adb", "devices"]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=False)
output = proc.communicate()[0].splitlines() #[0]="list of..", [1]=dsn, [2]=whitespace
del output[0] #Delete "list of devices attached" item
if len(output) == 1:
print "Device not detected. Please reconnect and rerun the script."
exit(1)
elif len(output) == 2:
dsn = output[0].split('\t')[0]
return dsn
else:
print "Please connect only 1 unit and rerun the script."
exit(1)
I first split the output into a list using splitlines(). This leaves me with a list of 3 items.
Then I simply delete the first item in the list ("List of devices attached") because I know I don't need it. But this feels so inelegant, and I know it will fail if the "adb devices" command output would ever change. But for a small script, would you really care? I want to work on better habits too, and I'm afraid this approach could lead to lazy habits.
Then I'm performing a split command on the first row in the list, with "\t" as a separator, and I set dsn equal to the first item in the resultant list (the serial number)
dsn = output[0].split('\t')[0]
The split is performed on a tab character that separates "V0124355SN" from "device". What I'm left with is the serial number. I can understand why I wrote this command, but should I make it clearer to those reading my code?
If android changes the output for this command at all, my script would be broken. But for such a basic script, do you think I should care?