鉴于共享库的短名称(例如gomp,而不是libgomp.so等),Python中确定该库是否已被加载的最佳方法是什么,如果是,请找到其完整路径名,以便ctypes句柄可以获得了吗?
答案 0 :(得分:1)
这是迄今为止我能够提出的最佳解决方案,但是从/proc/<pid>/maps
读取并对其内容进行字符串解析感觉有点蠢。
import re, ctypes, os.path
_WHITESPACE = re.compile('\s+')
def get_loaded_lib_pathname(lib_name):
soname = 'lib%s.so' % (lib_name,)
pid = os.getpid()
with open('/proc/%d/maps' % (pid,)) as f:
for line in f.readlines():
tokens = _WHITESPACE.split(line)
addrs, perms, offset, dev, inode, pathname = tokens[:6]
basename = os.path.basename(pathname)
if basename.startswith(soname):
return pathname
return None
def get_lib_handle(lib_name):
pathname = get_loaded_lib_pathname(lib_name)
if pathname is None:
return None
return ctypes.cdll.LoadLibrary(pathname)
libgomp = get_lib_handle('gomp')