11import sys , os
2+ import contextlib
23
34# find_library(name) returns the pathname of a library, or None.
45if os .name == "nt" :
@@ -117,11 +118,8 @@ def _get_soname(f):
117118 if not f :
118119 return None
119120 cmd = "/usr/ccs/bin/dump -Lpv 2>/dev/null " + f
120- f = os .popen (cmd )
121- try :
121+ with contextlib .closing (os .popen (cmd )) as f :
122122 data = f .read ()
123- finally :
124- f .close ()
125123 res = re .search (r'\[.*\]\sSONAME\s+([^\s]+)' , data )
126124 if not res :
127125 return None
@@ -138,11 +136,8 @@ def _get_soname(f):
138136 rv = f .close ()
139137 if rv == 10 :
140138 raise OSError ('objdump command not found' )
141- f = os .popen (cmd )
142- try :
139+ with contextlib .closing (os .popen (cmd )) as f :
143140 data = f .read ()
144- finally :
145- f .close ()
146141 res = re .search (r'\sSONAME\s+([^\s]+)' , data )
147142 if not res :
148143 return None
@@ -166,11 +161,8 @@ def _num_version(libname):
166161 def find_library (name ):
167162 ename = re .escape (name )
168163 expr = r':-l%s\.\S+ => \S*/(lib%s\.\S+)' % (ename , ename )
169- f = os .popen ('/sbin/ldconfig -r 2>/dev/null' )
170- try :
164+ with contextlib .closing (os .popen ('/sbin/ldconfig -r 2>/dev/null' )) as f :
171165 data = f .read ()
172- finally :
173- f .close ()
174166 res = re .findall (expr , data )
175167 if not res :
176168 return _get_soname (_findLib_gcc (name ))
@@ -182,20 +174,14 @@ def find_library(name):
182174 def _findLib_ldconfig (name ):
183175 # XXX assuming GLIBC's ldconfig (with option -p)
184176 expr = r'/[^\(\)\s]*lib%s\.[^\(\)\s]*' % re .escape (name )
185- f = os .popen ('/sbin/ldconfig -p 2>/dev/null' )
186- try :
177+ with contextlib .closing (os .popen ('/sbin/ldconfig -p 2>/dev/null' )) as f :
187178 data = f .read ()
188- finally :
189- f .close ()
190179 res = re .search (expr , data )
191180 if not res :
192181 # Hm, this works only for libs needed by the python executable.
193182 cmd = 'ldd %s 2>/dev/null' % sys .executable
194- f = os .popen (cmd )
195- try :
183+ with contextlib .closing (os .popen (cmd )) as f :
196184 data = f .read ()
197- finally :
198- f .close ()
199185 res = re .search (expr , data )
200186 if not res :
201187 return None
@@ -219,11 +205,8 @@ def _findSoname_ldconfig(name):
219205 # XXX assuming GLIBC's ldconfig (with option -p)
220206 expr = r'(\S+)\s+\((%s(?:, OS ABI:[^\)]*)?)\)[^/]*(/[^\(\)\s]*lib%s\.[^\(\)\s]*)' \
221207 % (abi_type , re .escape (name ))
222- f = os .popen ('/sbin/ldconfig -p 2>/dev/null' )
223- try :
208+ with contextlib .closing (os .popen ('/sbin/ldconfig -p 2>/dev/null' )) as f :
224209 data = f .read ()
225- finally :
226- f .close ()
227210 res = re .search (expr , data )
228211 if not res :
229212 return None
0 commit comments