用脚本实现定时打开应用程序

wen 实用脚本 2
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
定时打开应用程序脚本
功能:在指定时间或倒计时后自动打开指定的应用程序
适用系统:Windows / macOS / Linux
"""
import subprocess
import sys
import time
import os
from datetime import datetime, timedelta
import argparse
def open_application(app_path):
    """根据操作系统打开应用程序"""
    system = sys.platform
    try:
        if system == "win32":
            # Windows 系统
            os.startfile(app_path)
        elif system == "darwin":
            # macOS 系统
            subprocess.Popen(["open", app_path])
        else:
            # Linux 系统(大部分使用 xdg-open)
            subprocess.Popen(["xdg-open", app_path])
        print(f"[✓] 已成功打开应用程序: {app_path}")
        return True
    except Exception as e:
        print(f"[✗] 打开应用程序失败: {e}")
        return False
def wait_until_target(target_time):
    """等待直到目标时间"""
    while True:
        now = datetime.now()
        if now >= target_time:
            break
        remaining = (target_time - now).total_seconds()
        if remaining > 0:
            mins, secs = divmod(int(remaining), 60)
            hours, mins = divmod(mins, 60)
            print(f"\r⏳ 距离启动还有: {hours:02d}:{mins:02d}:{secs:02d}", end="")
            time.sleep(1)
    print()  # 换行
def wait_seconds(seconds):
    """等待指定秒数(带倒计时显示)"""
    for remaining in range(seconds, 0, -1):
        mins, secs = divmod(remaining, 60)
        hours, mins = divmod(mins, 60)
        print(f"\r⏳ 倒计时: {hours:02d}:{mins:02d}:{secs:02d}", end="")
        time.sleep(1)
    print()  # 换行
def parse_time_input(time_str):
    """
    解析时间输入,支持格式:
    - 绝对时间: HH:MM 或 HH:MM:SS
    - 相对时间: +秒 或 +分钟m 或 +小时h (+30, +5m, +1h)
    """
    time_str = time_str.strip()
    # 相对时间格式(以 + 开头)
    if time_str.startswith("+"):
        part = time_str[1:].lower()
        if part.endswith("h"):
            seconds = int(part[:-1]) * 3600
        elif part.endswith("m"):
            seconds = int(part[:-1]) * 60
        elif part.endswith("s"):
            seconds = int(part[:-1])
        else:
            # 默认解释为秒
            seconds = int(part)
        return datetime.now() + timedelta(seconds=seconds)
    # 绝对时间格式(HH:MM 或 HH:MM:SS)
    else:
        try:
            parts = time_str.split(":")
            if len(parts) == 2:
                hour, minute = int(parts[0]), int(parts[1])
                second = 0
            elif len(parts) == 3:
                hour, minute, second = int(parts[0]), int(parts[1]), int(parts[2])
            else:
                raise ValueError("时间格式错误")
            now = datetime.now()
            target = now.replace(hour=hour, minute=minute, second=second, microsecond=0)
            # 如果目标时间已经过去,则设置到明天
            if target <= now:
                target += timedelta(days=1)
                print(f"⏰ 当前时间已超过 {time_str},将安排到明天同一时间")
            return target
        except Exception as e:
            print(f"[✗] 时间格式解析错误: {e}")
            print("支持格式: HH:MM, HH:MM:SS, +秒, +分钟m, +小时h")
            sys.exit(1)
def main():
    parser = argparse.ArgumentParser(
        description="定时打开应用程序脚本",
        epilog="示例:\n"
               "  python scheduler.py notepad.exe 14:30\n"
               "  python scheduler.py 'C:\\Program Files\\App\\app.exe' +5m\n"
               "  python scheduler.py /Applications/Safari.app +1h\n"
               "  python scheduler.py firefox 09:00:00",
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument("app", help="应用程序路径或名称")
    parser.add_argument("time", help="启动时间 (HH:MM, HH:MM:SS, +秒, +分钟m, +小时h)")
    args = parser.parse_args()
    app_path = args.app
    time_input = args.time
    # 解析时间
    target_time = parse_time_input(time_input)
    print(f"📱 待启动应用: {app_path}")
    print(f"⏰ 目标时间: {target_time.strftime('%Y-%m-%d %H:%M:%S')}")
    print("-" * 50)
    # 计算等待秒数并等待
    wait_seconds_total = (target_time - datetime.now()).total_seconds()
    if wait_seconds_total > 0:
        if time_input.startswith("+"):
            wait_seconds(int(wait_seconds_total))
        else:
            wait_until_target(target_time)
    # 执行打开
    open_application(app_path)
if __name__ == "__main__":
    main()

使用说明

基本用法

在终端/命令提示符中运行:

用脚本实现定时打开应用程序

# 绝对时间模式 - 在指定时间打开
python scheduler.py notepad.exe 14:30
# 倒计时模式 - 等待指定秒数后打开
python scheduler.py chrome.exe +30
# 分钟倒计时
python scheduler.py "C:\Program Files\App\app.exe" +5m
# 小时倒计时
python scheduler.py /Applications/Safari.app +1h
# 带秒的绝对时间
python scheduler.py firefox 09:00:00

参数说明

参数 说明
app 应用程序路径(如 C:\Windows\notepad.exe)或仅名称(如 notepad.exe
time 启动时间,支持以下格式:
HH:MM - 指定小时和分钟
HH:MM:SS - 指定小时、分钟和秒
+秒 - 相对倒计时(秒)
+分钟m - 相对倒计时(分钟)
+小时h - 相对倒计时(小时)

跨平台支持

  • Windows: 自动使用 os.startfile()
  • macOS: 使用 open 命令
  • Linux: 使用 xdg-open 命令

示例场景

  1. 每天定时打开工作软件python scheduler.py outlook.exe 09:00
  2. 下班前提醒python scheduler.py notepad.exe +30m(30分钟后打开记事本)
  3. 定时打开浏览器python scheduler.py chrome.exe +1h

注意事项

  • 如果目标时间早于当前时间,脚本会自动将时间调整到明天
  • 倒计时模式下实时显示剩余时间
  • 请确保应用程序路径正确,或应用程序已在系统PATH中

这个脚本无需安装额外依赖,直接运行即可,如果您有更复杂的需求(如循环执行、多任务调度),我可以为您扩展功能。

抱歉,评论功能暂时关闭!