You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Windows可执行程序关闭后执行代码实现文件备份

实现Windows程序关闭后执行文件备份的方案

你可以通过subprocess模块启动目标程序并等待其退出,之后再执行备份操作。以下是修正后的可运行代码,解决你伪代码里的逻辑问题:

import subprocess
from dirsync import sync

# 配置路径,替换成实际路径
program_path = r"<prgm.exe Path>"  # 示例:r"C:\Program Files\MyApp\app.exe"
local_dir = r"<source Path>"
remote_dir = r"<target Path>"

# 程序启动前:从远程同步到本地(和你的伪逻辑一致)
sync(remote_dir, local_dir, 'sync', create=True, force=True)

# 启动目标程序,获取进程对象
proc = subprocess.Popen([program_path])

# 等待程序进程结束(替代你伪代码里的while循环)
proc.wait()

# 程序关闭后:从本地同步到远程
sync(local_dir, remote_dir, 'sync', create=True, force=True)

关键说明

  • subprocess.Popen()返回的进程对象可以直接用wait()方法阻塞当前脚本,直到目标程序退出,无需自行编写循环判断。
  • 如果需要非阻塞式监控(比如脚本同时处理其他任务),可以用proc.poll()方法循环检查:返回None表示进程仍在运行,返回数字表示已退出。示例:
    while proc.poll() is None:
        # 加入间隔等待,避免占用过高CPU
        import time
        time.sleep(1)
    
  • 路径建议用原始字符串(r"")避免转义字符问题,尤其是带空格或特殊字符的Windows路径。
  • 确保已安装dirsync:执行pip install dirsync完成安装

内容的提问来源于stack exchange,提问作者Dean Freeman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 09:54:23