简体   繁体   中英

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

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?

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.

Try:

import banana
import os.path

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM