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

如何通过Python脚本触发Windows任务计划程序中的指定任务?

如何用Python触发Windows任务计划程序中的特定任务

当然可以,有两种常用方法实现:

方法一:使用系统自带的schtasks命令行工具

这是最简单直接的方式,不需要额外安装依赖,利用Windows原生的schtasks命令来触发任务。

示例代码:

import subprocess

# 替换成你要触发的任务名称
target_task = "MyScheduledTask"

try:
    # 调用schtasks命令执行任务
    run_result = subprocess.run(
        ["schtasks", "/run", "/tn", target_task],
        check=True,
        capture_output=True,
        text=True
    )
    print(f"任务触发成功:{run_result.stdout.strip()}")
except subprocess.CalledProcessError as err:
    print(f"任务触发失败:{err.stderr.strip()}")

方法二:通过COM接口(win32com.client)操作

这种方式更原生,能实现更多任务计划相关的操作,不过需要先安装pywin32库。

先安装依赖:

pip install pywin32

示例代码:

import win32com.client

# 替换成目标任务名称
target_task = "MyScheduledTask"

try:
    # 连接到任务计划服务
    scheduler = win32com.client.Dispatch("Schedule.Service")
    scheduler.Connect()

    # 获取任务所在的文件夹(默认根路径,任务在子文件夹的话改成对应路径,比如"\\MySubFolder")
    task_folder = scheduler.GetFolder("\\")
    task = task_folder.GetTask(target_task)

    # 触发任务执行
    task.Run(None)
    print("任务触发成功")
except Exception as err:
    print(f"任务触发失败:{str(err)}")

注意事项

  • 如果任务位于自定义文件夹中,方法一中的/tn参数需要加上文件夹路径,比如"\\MyFolder\\MyTask";方法二中的GetFolder也要传入对应文件夹路径。
  • 运行Python脚本的用户需要有足够权限触发目标任务。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:32:39