Windows下Python调用os.system返回-1073741515错误排查
问题描述
参照《Byte of Python》教材的备份程序指引开发代码,运行后始终提示Backup FAILED。添加打印语句输出os.system接口的执行返回值,得到错误码-1073741515,检索不到该错误码对应含义,问题相关原代码如下:
import os import time # 1. 待备份的文件/目录列表 # Windows 示例路径 source = [r'C:\Users\ftbbo\PycharmProjects\helloworld'] # Mac OS X / Linux 示例路径 # source = ['/Users/swa/notes'] # 注意:路径含空格时可使用双引号包裹,或直接用r开头的原始字符串编写路径 # 2. 备份文件存储根目录 # Windows 示例路径 target_dir = 'C:\\PyBackup' # Mac OS X / Linux 示例路径 # target_dir = '/Users/swa/backup' # 3. 备份文件打包为zip格式 # 4. zip压缩包以当前日期时间命名 target = target_dir + os.sep + \ time.strftime('%Y%m%d%H%M%S') + '.zip' # 目标目录不存在则创建 if not os.path.exists(target_dir): os.mkdir(target_dir) # 5. 调用zip命令将文件打包到压缩包 zip_command = 'zip -r {0} {1}'.format(target, ' '.join(source)) # -r 参数代表递归打包目录下所有内容 # 执行备份 print('Zip command is:') print(zip_command) print('Running:') print(os.system(zip_command)) # 调试用打印返回值 if os.system(zip_command) == 0: print('Successful backup to', target) else: print('Backup FAILED')
错误根因
- 错误码
-1073741515转换为十六进制为0xC0000135,是Windows系统特有的STATUS_DLL_NOT_FOUND错误,本质是系统找不到调用的zip命令程序:Windows默认没有自带类Unix环境的zip命令行工具,执行os.system调用时无法启动对应程序,直接返回该错误。 - 原代码存在冗余逻辑:连续两次调用
os.system(zip_command),会导致压缩命令重复执行两次。
修复方案
方案1:安装zip命令行工具
下载Windows版本的zip命令行程序,将程序所在目录添加到系统环境变量PATH中,打开cmd窗口输入zip能正常输出帮助信息后,再运行脚本即可。
注意:需要把调试代码和判断逻辑处的重复调用合并,避免命令重复执行,修改后的执行段代码如下:
# 执行备份 print('Zip command is:') print(zip_command) print('Running:') res = os.system(zip_command) print(res) if res == 0: print('Successful backup to', target) else: print('Backup FAILED')
方案2:使用Python标准库实现压缩(推荐)
不需要依赖外部命令,用Python自带的zipfile模块实现压缩逻辑,跨平台兼容性更好,不会出现找不到外部程序的问题,完整修正代码如下:
import os import time import zipfile # 待备份路径列表 source = [r'C:\Users\ftbbo\PycharmProjects\helloworld'] # 备份存储根目录 target_dir = 'C:\\PyBackup' # 生成备份压缩包路径 target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip' # 目标目录不存在则创建 if not os.path.exists(target_dir): os.mkdir(target_dir) # 执行压缩 print('Running backup to', target) with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as zf: for src_path in source: # 遍历目录下所有文件 for root, dirs, files in os.walk(src_path): for file in files: file_full_path = os.path.join(root, file) # 计算压缩包内的相对路径,避免把磁盘全路径打包进去 arc_name = os.path.relpath(file_full_path, os.path.dirname(src_path)) zf.write(file_full_path, arc_name) print('Successful backup to', target)
内容的提问来源于stack exchange,提问作者Clayton Collins
相关产品推荐
相关产品推荐

