python的dll文件在哪_如何在python中搜索并获取DLL文件的目录

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值