How can I search and get the directory of a DLL fi

2019-07-23 08:16发布

问题:

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__)