Python 3.11调用filedialog选大文件触发SIGSEGV错误求助
问题:Python文件选择对话框加载大文件触发SIGSEGV错误
问题背景
我是Python新手,使用以下代码调用文件选择对话框:
# Constant c_dir = '/Users/sapfinance/PycharmProjects/RFBIBL00' C_FILE_SEP = '|' Fichier1 = filedialog.askopenfile(initialdir=c_dir) Fichier2 = filedialog.askopenfile(initialdir=c_dir)
异常现象
- 当第一个选择300MB以上的大文件、第二个选择小文件时,程序崩溃,提示:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) - 但如果先选小文件、再选大文件则运行正常
环境信息
- 设备:2023款MBP(ARM-64架构)
- Python版本:3.11.1
- macOS版本:13.2 (22D49)
错误日志
------------------------------------- Translated Report (Full Report Below) ------------------------------------- Process: Python [75896] Path: /Library/Frameworks/Python.framework/Versions/3.11/Resources/Python.app/Contents/MacOS/Python Identifier: org.python.python Version: 3.11.1 (3.11.1) Code Type: ARM-64 (Native) Parent Process: pycharm [49477] Responsible: pycharm [49477] User ID: 501 Date/Time: 2023-02-13 17:42:44.2803 +0100 OS Version: macOS 13.2 (22D49) Report Version: 12 Anonymous UUID: CC935EEC-AECF-735E-06B3-40216C7B759F Sleep/Wake UUID: BE7F527D-88BD-4A69-8B1B-662C43878116 Time Awake Since Boot: 470000 seconds Time Since Wake: 14851 seconds System Integrity Protection: enabled Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x000000000000001e Exception Codes: 0x0000000000000001, 0x000000000000001e Termination Reason: Namespace SIGNAL, Code 11 Segmentation fault: 11 Terminating Process: exc handler [75896] VM Region Info: 0x1e is not in any region. Bytes before following region: 105553518919650 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL UNUSED SPACE AT START ---> MALLOC_NANO (reserved) 600018000000-600020000000 [128.0M] rw-/rwx SM=NUL ...(unallocated)
原因分析与解决方案
可能原因
这个错误是段错误(Segmentation Fault),意味着程序试图访问不属于自身的内存区域。结合场景判断,大概率是ARM架构macOS上Python 3.11的Tkinter文件对话框存在兼容性bug:
askopenfile默认会尝试将文件内容一次性加载到内存,大文件的内存操作触发了管理异常;- ARM-64版本的Python与Tkinter交互层存在内存访问漏洞,特定调用顺序(先选大文件再选小文件)会触发该问题。
解决方法
- 改用路径选择而非直接打开文件:
用filedialog.askopenfilename替代askopenfile,仅获取文件路径,后续按需手动分块读取大文件,避免一次性加载内存:from tkinter import filedialog c_dir = '/Users/sapfinance/PycharmProjects/RFBIBL00' C_FILE_SEP = '|' # 仅获取文件路径 file_path1 = filedialog.askopenfilename(initialdir=c_dir) file_path2 = filedialog.askopenfilename(initialdir=c_dir) # 分块读取大文件示例 if file_path1: with open(file_path1, 'r') as f1: for line in f1: # 逐行处理内容 pass - 升级Python版本:
Python 3.11后续版本可能修复了该ARM架构下的Tkinter bug,建议升级到3.11.3及以上版本; - 更换Python安装源:
如果升级后问题仍存在,可尝试使用Homebrew安装的Python(而非官方框架版),或改用PyPy等其他Python实现。
内容的提问来源于stack exchange,提问作者Philippe gauthier
相关产品推荐
相关产品推荐

