How can I search and get the directory of a DLL file in python

僤鯓⒐⒋嵵緔 提交于 2019-12-24 11:16:17

问题


Let's say if I have a dll file called banana.dll, and I have a module called banana.py which will use ctypes to load banana.dll, and they are stored in the same directory, for exmaple c:\Python27\lib in Windows.

Now I create a new python file called testing.py in other directory (for example c:\user\desktop ) which will import the banana.py module. But since the current working directory is the directory where testing.py is stored. So I need to manually change the directory to c:\Python27\lib by hardcoding it.

But is there a smarter way that I can search the path where banana.dll is stored?


回答1:


If you have pywin32 installed:

import _win32sysloader
mod = 'banana'
path_to_mod = _win32sysloader.GetModuleFilename(mod) or _win32sysloader.LoadModule(mod)

Or

import win32api
mod = 'banana'
path_to_mod = win32api.GetModuleFileName(win32api.LoadLibrary(mod))

If you don't have pywin32, you can use ctypes to access win32 api:

import ctypes
from ctypes.wintypes import HANDLE, LPWSTR, DWORD

GetModuleFileName = ctypes.windll.kernel32.GetModuleFileNameW
GetModuleFileName.argtypes = HANDLE, LPWSTR, DWORD
GetModuleFileName.restype = DWORD

mod = 'banana'
MAX_PATH = 260
dll = ctypes.CDLL(mod) or ctypes.WINDLL(mod)
buf = ctypes.create_unicode_buffer(MAX_PATH)
GetModuleFileName(dll._handle, buf, MAX_PATH)
path_to_mod = buf.value

Don't forget to handle WindowsError and other possible exceptions.




回答2:


Try:

import banana
import os.path

module_dirname = os.path.dirname(banana.__file__)


来源:https://stackoverflow.com/questions/11007896/how-can-i-search-and-get-the-directory-of-a-dll-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!