如何在子进程生成指定文件时终止该进程?
解决方案:监控目标文件并终止子进程
核心思路是用subprocess.Popen启动非阻塞进程,循环检查目标文件是否生成完成,同时兼顾超时和进程自行终止的情况。
实现代码
import subprocess import os import time # 替换为你的实际配置 target_summary_file = "/absolute/path/to/your/summary_file.csv" # 建议用绝对路径 max_timeout = 2700 # 最大等待时长(45分钟) check_interval = 30 # 每隔30秒检查一次状态 # 启动exe进程(非阻塞) try: proc = subprocess.Popen(cmd_split) except Exception as e: print(f"启动exe失败: {str(e)}") exit(1) start_timestamp = time.time() proc_naturally_exited = False while True: # 检查进程是否已经自行退出 exit_code = proc.poll() if exit_code is not None: print(f"exe进程自行终止,返回码: {exit_code}") proc_naturally_exited = True break # 检查是否超时 elapsed_time = time.time() - start_timestamp if elapsed_time >= max_timeout: print(f"等待超时({max_timeout}秒),强制终止exe进程") proc.terminate() proc.wait() # 等待进程彻底退出 break # 检查目标文件是否存在且完成写入 if os.path.exists(target_summary_file): # 二次校验:等待2秒后确认文件大小不再变化,避免文件未写完 initial_size = os.path.getsize(target_summary_file) time.sleep(2) updated_size = os.path.getsize(target_summary_file) if initial_size == updated_size: print(f"检测到汇总文件已生成完成,终止exe进程") proc.terminate() proc.wait() break else: print("汇总文件仍在写入,继续等待...") # 等待指定间隔后再次检查 time.sleep(check_interval) # 后续处理逻辑 if not proc_naturally_exited: print("exe进程已被主动终止")
关键细节说明
- 非阻塞启动:用
Popen替代run,主程序可同时监控进程和文件状态,不会被阻塞。 - 文件完整性校验:单纯检测文件存在可能不准确(exe可能先创建文件再写入内容),增加文件大小稳定校验,确保文件已写完。
- 进程终止方式:优先用
terminate()发送终止信号,比kill()更优雅;若terminate()无效,可替换为proc.kill()强制杀死。 - 绝对路径:目标文件建议用绝对路径,避免因工作目录不同导致的文件检测失败。
内容的提问来源于stack exchange,提问作者mineself
相关产品推荐
相关产品推荐

