在 Windows/Linux 上使用 python3 脚本检查可执行文件是 32 位还是 64 位 [英] Checking if an executable is 32-bit or 64-bit with a python3 script on Windows/Linux
问题描述
我正在用 Python3 编写软件(更具体地说:Python 3.8.1
).在某些时候,软件需要检查某个任意可执行文件是 64 位还是 32 位.经过一番研究,我发现了以下帖子:
I'm writing software in Python3 (more specifically: Python 3.8.1
). At some point, the software needs to check if some arbitrary executable is 64-bit or 32-bit. After some research, I found the following post:
在这篇文章中,提供了以下解决方案:
In this post, the following solution is offered:
subprocess.call(['dumpbin', '/HEADERS', 'test2.exe', '|', 'find', '"machine"'])
不幸的是,这在 Python 3.8.1
中不起作用.这篇文章已有近 8 年的历史,可以追溯到 Python 2.x
时代.
Unfortunately, this doesn't work in Python 3.8.1
. That post is almost 8 years old and dates back to the Python 2.x
days.
如何在 Python 3.x
中测试 64 位?我需要一个适用于 Linux 和 Windows 10 的解决方案.
How can I test for 64-bitness from within Python 3.x
? I need a solution for both Linux and Windows 10.
Windows 相关注意事项:
显然是 DumpBin
解决方案(参见 检查 exe 是 32 位还是 64 位 帖子)需要安装 Visual Studio.这对我来说是禁忌.我的 Python3 软件应该可以在任何 Windows 10 计算机上运行.
EDITS :
Windows-related note:
Apparently theDumpBin
solution (see Checking if an exe is 32 bit or 64 bit post) requires Visual Studio to be installed. That's a no-no for me. My Python3 software should run on any Windows 10 computer.
Linux 相关注意事项:
在 Linux 上,我不需要测试 PE 格式的可执行文件.只需 Linux 可执行文件即可.
Linux-related note:
On Linux, I don't neet to test PE format executables. Just Linux executables are fine.
推荐答案
检测 ELF 二进制文件(即 Linux)的 64 位很容易,因为它总是在标题中的同一个位置:
Detecting the 64-bitness of ELF binaries (i.e. Linux) is easy, because it's always at the same place in the header:
def is_64bit_elf(filename):
with open(filename, "rb") as f:
return f.read(5)[-1] == 2
我没有 Windows 系统,所以我无法测试这个,但这可能适用于 Windows:
I don't have a Windows system, so I can't test this, but this might work on Windows:
def is_64bit_pe(filename):
import win32file
return win32file.GetBinaryType(filename) == 6
这篇关于在 Windows/Linux 上使用 python3 脚本检查可执行文件是 32 位还是 64 位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!