python - 如何检查文件是否是来自 Python 的 macOS 可执行文件?
问题描述
例如,给定:
$ cd /Applications/Xcode.app/Contents/MacOS
$ file Xcode
Xcode: Mach-O 64-bit executable x86_64
和:
$ cd /Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A
$ file IDEKit
IDEKit: Mach-O 64-bit dynamically linked shared library x86_64
我希望能够做file
正在做的事情,特别是检查文件是否是可执行文件,但以编程方式来自 Python。
我知道我可以调用file
命令并解析 Python 的结果,但是有没有更好的方法不涉及调用file
?
注意:
$ ls -l IDEKit
-rwxr-xr-x 1 root wheel 17256912 Apr 5 17:42 IDEKit*
和:
$ ls -l Xcode
-rwxr-xr-x 1 root wheel 44416 Apr 11 13:40 Xcode*
即,就文件系统权限位而言,它们都是“可执行的”,但只是Xcode
真正的可执行文件。
解决方案
事实证明,macholib允许您从 Python 读取和检查文件的 Mach-O 标头(如果有的话)。所以代码如下:
def read_macho_headers( file ):
try:
return MachO.MachO( file ).headers
except Exception: # not a Mach-O file
return None
def is_macho_exe( macho_headers ):
filetype = macho_headers[0].header.filetype
return filetype == mach_o.MH_EXECUTE
将工作。
推荐阅读
- yocto - 无法构建元英特尔的 ixgbe
- python - 使用函数到数据流的作业
- jbpm - jBPM:创建运行时引擎时没有此类方法错误
- javascript - 重构以反应钩子后,地图中的复选框未在数组更新时更新
- sql - 是否可以使用点表示法从 R 中的数据库中的多个表中查询数据?
- javascript - 如何使用 Javascript 识别 HTML 元素的选择器?
- java - Android 设备中的 OpenCV Java API 或 OpenCV C++ API?
- python - Pygame 在 IDLE 中工作,但在 Spyder 中我得到 AttributeError
- javascript - Swiper js自动播放滑块
- mysql - MYSQL 不允许从函数返回结果集