【发布时间】:2020-06-12 20:22:21
【问题描述】:
我将简要解释一下代码。我想在特定的二进制文件 (exe) 中添加一些 .dll 的内容。当我需要它时,我将从这个二进制文件中删除 dll。这个过程在 CI/CD 过程中会表现得更好。 以下代码完美适用于 32 位 python 解释器和 32 位二进制文件。
问题报告: 即使使用 64 位解释器,我也无法对 64 位二进制文件执行此过程。 使用 64 位解释器,我无法加载 32 位或 64 位二进制文件。问题是是否有一种方法或类似 win32api 的库,比如“win64api”?
尝试的结果总是:
pywintypes.error: (193, 'LoadLibrary', '% 1 is not a valid Win32 application.')
我的问题: 是否有任何表单/模块/库可以对 64 位文件执行此任务?
环境和示例二进制文件:
完美运行:
- Python 3.7.7(标签/v3.7.7:d7c567b08f,2020 年 3 月 10 日,09:44:33)[MSC v.1900 32 位 (Intel)] 在 win32 上
- https://www.python.org/ftp/python/3.7.7/python-3.7.7.exe(或任何 其他 32 位二进制文件)
不起作用:
Python 3.7.7(tags/v3.7.7:d7c567b08f,2020 年 3 月 10 日,10:41:24)[MSC v.1900 64 位 (AMD64)] 在 win32 上
https://www.python.org/ftp/python/3.7.7/python-3.7.7-amd64.exe(或 任何其他 64 位二进制文件)
当地规范
platform.platform() >> 'Windows-10-10.0.18362-SP0'
platform.uname() >> uname_result(system='Windows', 节点='DESKTOP-SER206K',发布='10',版本='10.0.18362', machine='AMD64', processor='AMD64 Family 21 Model 2 Stepping 0, 正品AMD')
示例代码
import os
import win32api
import win32con
import base64
binary = "C:\\Users\\Guto\\Documents\\python\\python-3.7.7.exe"
assert os.path.exists(binary)
PATH_RC = "C:\\Users\\Guto\\Documents\\python\\sqlite3.dll"
assert os.path.exists(PATH_RC)
# Get a handle that can be used by the UpdateResource()
h = win32api.BeginUpdateResource(binary, 0)
rc_content = open(PATH_RC, "rb").read()
rc_content_b64 = base64.b64encode(rc_content)
win32api.UpdateResource(h, win32con.RT_STRING, "rc_content_b64", rc_content_b64)
# End the update resource of the handle.
win32api.EndUpdateResource(h, 0)
#at this point, I have a modified binary
#then I will access that information
h = win32api.LoadLibrary(binary)
r_list = win32api.EnumResourceNames(h, win32con.RT_STRING)
#Find and Load a resource component
resource = win32api.LoadResource(h, win32con.RT_STRING, "rc_content_b64")
new_rc_content = base64.b64decode(resource)
#Write the DLL again
NEW_PATH_RC = "C:\\Users\\Guto\\Documents\\python\\new_dll.dll"
with open(NEW_PATH_RC, "wb") as f:
f.write(new_rc_content)
【问题讨论】:
-
@IInspectable thx,我更新了问题报告!
-
我仍然不确定我是否完全理解你想要完成的事情。当我读到它时,您有一个二进制 (.exe) 文件,并希望将一个库 (.dll) 作为二进制资源嵌入其中,最终将在稍后阶段解压缩。对吗?
-
@IInspectable 是的,就是这样!
-
@mar 我不熟悉 Python。如果你是,请随时将我的评论音译成答案。
标签: python winapi pywin32 win32com