patternpythonMinor
Output of 'ldd' to dictionary
Viewed 0 times
dictionarylddoutput
Problem
I want to use the output of the terminal command
And use it to build a dictionary that uses the library name as key and the path to the library as value. I've come up with this little Python snippet:
It works fine for my needs but I'm at the point where I don't want my code to just work but want it optimized and well structured/programmed. How can I improve this snippet?
EDIT: Note that I do not want the address (ie 0xbxxxxxx) in my dictionary
ldd:root@kali-vm:~/Desktop# ldd simple
linux-gate.so.1 => (0xb7722000)
libcurl-gnutls.so.4 => /usr/lib/i386-linux-gnu/libcurl-gnutls.so.4 (0xb769c000)
libc.so.6 => /lib/i386-linux-gnu/i686/cmov/libc.so.6 (0xb7539000)
libidn.so.11 => /usr/lib/i386-linux-gnu/libidn.so.11 (0xb7505000)And use it to build a dictionary that uses the library name as key and the path to the library as value. I've come up with this little Python snippet:
# Get List of Librairies in Dictionary
lddOut = subprocess.check_output(['ldd', fileName])
libraries = {}
for line in lddOut.splitlines():
arr = line.split(" => ")
library = arr[0].strip('\t')
try:
path = arr[1].split(' (0x')[0]
except:
pass
libraries[library] = pathIt works fine for my needs but I'm at the point where I don't want my code to just work but want it optimized and well structured/programmed. How can I improve this snippet?
EDIT: Note that I do not want the address (ie 0xbxxxxxx) in my dictionary
Solution
This kind of parsing by pattern matching is much better done using a regular expression.
import re
libraries = {}
for line in ldd_out.splitlines():
match = re.match(r'\t(.*) => (.*) \(0x', line)
if match:
libraries[match.group(1)] = match.group(2)Code Snippets
import re
libraries = {}
for line in ldd_out.splitlines():
match = re.match(r'\t(.*) => (.*) \(0x', line)
if match:
libraries[match.group(1)] = match.group(2)Context
StackExchange Code Review Q#48729, answer score: 5
Revisions (0)
No revisions yet.