Python调用子进程处理图片标签:迭代后自动终止子进程问询
解决方法
问题根源在于你使用的exiftool(-k).exe——这个带-k后缀的版本是ExifTool专门做的"暂停版",执行完任务后会自动挂起等待用户按回车,这就是你每次都要手动触发才能继续的原因。
1. 替换为无暂停的ExifTool版本
最简单直接的解决方式是换成不带-k的标准exiftool.exe:
- 可以直接去ExifTool官方下载标准版;
- 嫌麻烦的话,直接复制一份
exiftool(-k).exe并重命名为exiftool.exe,它就会自动取消暂停逻辑。
修改代码里的路径:
exifToolPath = r'C:\some path\exiftool.exe'
2. 优化子进程处理逻辑(避免残留进程)
即使解决了暂停问题,处理子进程时也建议用更安全的方式,确保每个文件处理完后进程能正常终止:
推荐用subprocess.run()(自动等待进程结束)
import os import subprocess exifToolPath = r'C:\some path\exiftool.exe' folder_dir = r"C:\some path" for file in os.listdir(folder_dir): path = os.path.abspath(os.path.join(folder_dir, file)) # 简化后缀判断 if file.lower().endswith((".png", ".jpg", ".jpeg")): # run方法会自动等待子进程完成,无需手动处理终止 result = subprocess.run( [exifToolPath, path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, shell=False ) infoDict = {} # 按行解析输出,更严谨处理分割逻辑 for line in result.stdout.splitlines(): if ': ' in line: key, value = line.split(': ', 1) infoDict[key.strip()] = value.strip() # 这里可以添加写入Excel等后续操作 for k, v in infoDict.items(): print(k, ':', v)
特殊情况:必须保留带-k的版本
如果因为某些限制不能替换exe,可以通过给子进程发送回车信号,或者强制终止进程:
import os import subprocess exifToolPath = r'C:\some path\exiftool(-k).exe' folder_dir = r"C:\some path" for file in os.listdir(folder_dir): path = os.path.abspath(os.path.join(folder_dir, file)) if file.lower().endswith((".png", ".jpg", ".jpeg")): process = subprocess.Popen( [exifToolPath, path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, # 开启输入管道 text=True, shell=False ) # 读取所有输出,同时发送回车触发进程结束 output, _ = process.communicate(input='\n') infoDict = {} for line in output.splitlines(): if ': ' in line: key, value = line.split(': ', 1) infoDict[key.strip()] = value.strip() for k, v in infoDict.items(): print(k, ':', v) # 保险起见,强制终止进程 process.terminate()
内容的提问来源于stack exchange,提问作者dorado
相关产品推荐
相关产品推荐

