如何在python中搜索并获取DLL文件的目录 [英] How can I search and get the directory of a DLL file in python

查看:1332
本文介绍了如何在python中搜索并获取DLL文件的目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 banana.dll dll 文件,我有一个名为 banana.py 将使用 ctypes 加载 banana.dll 并且它们存储在相同的目录中,例如Windows中的示例 c:\Python27\lib



现在,我在其他目录中创建一个名为 testing.py 的新python文件(例如 c:\user\desktop ),它将导入 banana.py 模块。但由于当前工作目录是存储 test.py 的目录。所以我需要通过硬编码来手动将目录更改为 c:\Python27\lib



但是有一种更聪明的方法,我可以搜索存储 banana.dll 的路径吗?

解决方案

如果您已安装pywin32:

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

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

如果没有pywin32您可以使用ctypes访问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 ='香蕉'
MAX_PATH = 260
dll = ctypes.CDLL(mod)或ctypes.WIND LL(mod)
buf = ctypes.create_unicode_buffer(MAX_PATH)
GetModuleFileName(dll._handle,buf,MAX_PATH)
path_to_mod = buf.value

不要忘记处理WindowsError和其他可能的异常。


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.

这篇关于如何在python中搜索并获取DLL文件的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆