Debian Codegraph @

DisplayCAL/taskscheduler.py

raw
1 """Task Scheduler interface.
2
3 Currently only implemented for Windows (Vista and up).
4 The implementation is currently minimal and incomplete when it comes to
5 creating tasks (all tasks are created for the 'INTERACTIVE' group and with
6 only logon triggers and exec actions available).
7
8 Note that most of the functionality requires administrative privileges.
9
10 Has a dict-like interface to query existing tasks.
11
12 >>> ts = TaskScheduler()
13
14 Check if task "name" exists:
15 >>> "name" in ts
16 or
17 >>> ts.has_task("name")
18
19 Get existing task "name":
20 >>> task = ts["name"]
21 or
22 >>> ts.get("name")
23
24 Run task:
25 >>> task.Run()
26 or
27 >>> ts.run("name")
28
29 Get task exit and startup error codes:
30 >>> exitcode, startup_error_code = task.GetExitCode()
31 or
32 >>> exitcode, startup_error_code = ts.get_exit_code(task)
33
34 Create a new task to be run under the current user account at logon:
35 >>> task = ts.create("name", "program.exe", ["arg1", "arg2", "argn"])
36
37 """
38
39 # Standard Library Imports
40 from __future__ import annotations
41
42 import codecs
43 import os
44 import subprocess as sp
45 import tempfile
46 from typing import TYPE_CHECKING, Any
47
48 # Third Party Imports
49 import pywintypes
50 import winerror
51
52 # Local Imports
53 from DisplayCAL.meta import NAME as APPNAME
54 from DisplayCAL.safe_print import ENC
55 from DisplayCAL.util_str import indent, universal_newlines
56 from DisplayCAL.util_win import run_as_admin
57
58 if TYPE_CHECKING:
59 from collections.abc import Iterator
60
61 from win32com.taskscheduler import ITaskScheduler
62
63
64 RUNLEVEL_HIGHESTAVAILABLE = "HighestAvailable"
65 RUNLEVEL_LEASTPRIVILEGE = "LeastPrivilege"
66
67 MULTIPLEINSTANCES_IGNORENEW = "IgnoreNew"
68 MULTIPLEINSTANCES_STOPEXISTING = "StopExisting"
69
70
71 class _Dict2XML(dict):
72 """Base class for dictionary to XML conversion.
73
74 Uses the dictionary keys as XML element names and the values as
75 element values. Special keys 'cls_name' and 'cls_attr' are used to set
76 the class name and attributes of the root element.
77 """
78
79 def __init__(self, *args, **kwargs) -> None:
80 dict.__init__(self, *args, **kwargs)
81 if "cls_name" not in self:
82 self["cls_name"] = self.__class__.__name__
83 if "cls_attr" not in self:
84 self["cls_attr"] = ""
85
86 def __str__(self) -> str:
87 """Convert the dict to a string representation in XML format.
88
89 Returns:
90 str: The string representation of the dict in XML format.
91 """
92 items = []
93 for name in self:
94 value = self[name]
95 if isinstance(value, bool):
96 value = str(value).lower()
97 elif name in ("cls_name", "cls_attr") or not value:
98 continue
99 if isinstance(value, _Dict2XML):
100 item = str(value)
101 else:
102 cc = "".join(f"{part[0].upper()}{part[1:]}" for part in name.split("_"))
103 if isinstance(value, (list, tuple)):
104 item = "\n".join([str(item) for item in value])
105 else:
106 item = f"<{cc}>{value}</{cc}>"
107 items.append(indent(item, " "))
108 return """<{cls_name}{cls_attr}>
109 {items}
110 </{cls_name}>""".format(
111 cls_name=self["cls_name"],
112 cls_attr=self["cls_attr"],
113 items="\n".join(items),
114 )
115
116
117 class _Trigger(_Dict2XML):
118 """Base class for triggers.
119
120 Args:
121 interval (str): The interval between repetitions in ISO 8601 format.
122 duration (str): The duration for which the trigger should repeat in
123 ISO 8601 format.
124 stop_at_duration_end (bool): Whether to stop the trigger at the end of
125 the duration.
126 enabled (bool): Whether the trigger is enabled.
127 """
128
129 def __init__(
130 self,
131 interval: None | str = None,
132 duration: None | str = None,
133 stop_at_duration_end: bool = False,
134 enabled: bool = True,
135 ) -> None:
136 repetition = (
137 interval
138 and _Dict2XML(
139 interval=interval,
140 duration=duration,
141 stop_at_duration_end=stop_at_duration_end,
142 cls_name="Repetition",
143 )
144 ) or ""
145 _Dict2XML.__init__(self, repetition=repetition, enabled=enabled)
146
147
148 class CalendarTrigger(_Trigger):
149 """Trigger for a calendar event.
150
151 Args:
152 start_boundary (str): The start boundary in ISO 8601 format.
153 days_interval (int): The interval in days for the trigger.
154 weeks_interval (int): The interval in weeks for the trigger.
155 days_of_week (list[int]): The days of the week for the trigger (1=
156 Sunday, 2=Monday, ..., 7=Saturday).
157 months (list[int]): The months for the trigger (1=January, 2=February,
158 ..., 12=December).
159 days_of_month (list[int]): The days of the month for the trigger (1-31).
160 """
161
162 def __init__(
163 self,
164 start_boundary: str = "2019-09-17T00:00:00",
165 days_interval: int = 1,
166 weeks_interval: int = 0,
167 days_of_week: None | list[int] = None,
168 months: None | list[int] = None,
169 days_of_month: None | list[int] = None,
170 **kwargs,
171 ) -> None:
172 _Trigger.__init__(self, **kwargs)
173 self["start_boundary"] = start_boundary
174 self["schedule_by_day"] = (
175 days_interval
176 and _Dict2XML(days_interval=days_interval, cls_name="ScheduleByDay")
177 ) or ""
178 self["schedule_by_week"] = (
179 weeks_interval
180 and _Dict2XML(
181 days_of_week=_Dict2XML(items=days_of_week, cls_name="DaysOfWeek"),
182 weeks_interval=weeks_interval,
183 cls_name="ScheduleByWeek",
184 )
185 ) or ""
186 self["schedule_by_month"] = (
187 months
188 and _Dict2XML(
189 days_of_month=_Dict2XML(items=days_of_month, cls_name="DaysOfMonth"),
190 months=_Dict2XML(items=months, cls_name="Months"),
191 cls_name="ScheduleByMonth",
192 )
193 ) or ""
194
195
196 class LogonTrigger(_Trigger):
197 """Trigger for when the user logs on."""
198
199
200 class ResumeFromSleepTrigger(_Trigger):
201 """Trigger for when the system resumes from sleep."""
202
203 def __init__(self, *args, **kwargs) -> None:
204 _Trigger.__init__(self, *args, **kwargs)
205 self["subscription"] = (
206 """&lt;QueryList&gt;&lt;Query Id="0" Path="System"&gt;&lt;"""
207 """Select Path="System"&gt;*[System[Provider["""
208 """@Name='Microsoft-Windows-Power-Troubleshooter'] and """
209 """(Level=4 or Level=0) and """
210 """(EventID=1)]]&lt;/Select&gt;&lt;/Query&gt;&lt;/QueryList&gt;"""
211 )
212 self["cls_name"] = "EventTrigger"
213
214
215 class ExecAction(_Dict2XML):
216 """Exec action.
217
218 Args:
219 cmd (str): The command to run.
220 args (list[str]): The arguments to pass to the command. Defaults to None,
221 which means no arguments.
222 """
223
224 def __init__(self, cmd: str, args: None | list[str] = None) -> None:
225 # Filter any None values
226 args = [arg for arg in args if arg is not None]
227 _Dict2XML.__init__(
228 self,
229 command=cmd,
230 arguments=(args and sp.list2cmdline(args)) or None,
231 cls_name="Exec",
232 )
233
234
235 class Task(_Dict2XML):
236 """Task Scheduler task.
237
238 Args:
239 name (str): The name of the task.
240 author (str): The author of the task.
241 description (str): The description of the task.
242 group_id (str): The group ID for the task.
243 run_level (str): The run level for the task.
244 multiple_instances_policy (str): The policy for multiple instances.
245 disallow_start_if_on_batteries (bool): Whether to disallow starting
246 the task if on batteries.
247 stop_if_going_on_batteries (bool): Whether to stop the task if
248 going on batteries.
249 allow_hard_terminate (bool): Whether to allow hard termination of
250 the task.
251 start_when_available (bool): Whether to start the task when
252 available.
253 run_only_if_network_available (bool): Whether to run the task only
254 if the network is available.
255 duration (str): The duration for which the task should run.
256 wait_timeout (str): The timeout for waiting for the task to finish.
257 stop_on_idle_end (bool): Whether to stop the task when the system
258 goes idle.
259 restart_on_idle (bool): Whether to restart the task when the system
260 goes idle.
261 allow_start_on_demand (bool): Whether to allow starting the task on
262 demand.
263 enabled (bool): Whether the task is enabled.
264 hidden (bool): Whether the task is hidden.
265 run_only_if_idle (bool): Whether to run the task only if the system
266 is idle.
267 wake_to_run (bool): Whether to wake the system to run the task.
268 execution_time_limit (str): The execution time limit for the task.
269 priority (int): The priority of the task.
270 triggers (list[_Trigger]): List of triggers for this task, e.g.:
271 [LogonTrigger(), CalendarTrigger(), ResumeFromSleepTrigger()].
272 actions (list[ExecAction]): List of actions for this task, e.g.:
273 [ExecAction("program.exe", ["arg1", "arg2"])].
274 """
275
276 def __init__(
277 self,
278 name: str = "",
279 author: str = "",
280 description: str = "",
281 group_id: str = "S-1-5-4",
282 run_level: str = RUNLEVEL_LEASTPRIVILEGE,
283 multiple_instances_policy: str = MULTIPLEINSTANCES_IGNORENEW,
284 disallow_start_if_on_batteries: bool = False,
285 stop_if_going_on_batteries: bool = False,
286 allow_hard_terminate: bool = True,
287 start_when_available: bool = False,
288 run_only_if_network_available: bool = False,
289 duration: None | str = None,
290 wait_timeout: None | str = None,
291 stop_on_idle_end: bool = False,
292 restart_on_idle: bool = False,
293 allow_start_on_demand: bool = True,
294 enabled: bool = True,
295 hidden: bool = False,
296 run_only_if_idle: bool = False,
297 wake_to_run: bool = False,
298 execution_time_limit: str = "PT72H",
299 priority: int = 5,
300 triggers: None | list[_Trigger] = None,
301 actions: None | list[ExecAction] = None,
302 ) -> None:
303 idle_settings = {
304 "duration": duration,
305 "wait_timeout": wait_timeout,
306 "stop_on_idle_end": stop_on_idle_end,
307 "restart_on_idle": restart_on_idle,
308 }
309 kwargs = {
310 "allow_hard_terminate": allow_hard_terminate,
311 "allow_start_on_demand": allow_start_on_demand,
312 "disallow_start_if_on_batteries": disallow_start_if_on_batteries,
313 "enabled": enabled,
314 "execution_time_limit": execution_time_limit,
315 "hidden": hidden,
316 "multiple_instances_policy": multiple_instances_policy,
317 "priority": priority,
318 "run_only_if_idle": run_only_if_idle,
319 "start_when_available": start_when_available,
320 "stop_if_going_on_batteries": stop_if_going_on_batteries,
321 "wake_to_run": wake_to_run,
322 }
323 settings = _Dict2XML(kwargs, cls_name="Settings")
324 settings["idle_settings"] = _Dict2XML(idle_settings, cls_name="IdleSettings")
325
326 kwargs = {}
327 kwargs["registration_info"] = _Dict2XML(
328 author=author,
329 description=description,
330 URI=f"\\{name}",
331 cls_name="RegistrationInfo",
332 )
333 kwargs["triggers"] = _Dict2XML(items=triggers or [], cls_name="Triggers")
334 kwargs["principals"] = _Dict2XML(
335 items=[
336 _Dict2XML(
337 group_id=group_id,
338 run_level=run_level,
339 cls_name="Principal",
340 cls_attr=' id="Author"',
341 )
342 ],
343 cls_name="Principals",
344 )
345 kwargs["settings"] = settings
346 kwargs["actions"] = _Dict2XML(
347 items=actions or [], cls_name="Actions", cls_attr=' Context="Author"'
348 )
349 kwargs["cls_attr"] = (
350 ' version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"'
351 )
352 _Dict2XML.__init__(self, kwargs)
353
354 def add_exec_action(self, cmd: str, args: None | list[str] = None) -> None:
355 """Add an exec action to the task.
356
357 Args:
358 cmd (str): The command to run.
359 args (list[str]): The arguments to pass to the command. Defaults to
360 None, which means no arguments.
361 """
362 self["actions"]["items"].append(ExecAction(cmd, args))
363
364 def add_logon_trigger(self, enabled: bool = True) -> None:
365 """Add a logon trigger to the task.
366
367 Args:
368 enabled (bool): Whether the logon trigger is enabled. Defaults to
369 True.
370 """
371 self["triggers"]["items"].append(LogonTrigger(enabled))
372
373 def write_xml(self, xmlfilename: str) -> None:
374 """Write the task to an XML file.
375
376 Args:
377 xmlfilename (str): The filename to write the XML to.
378 """
379 with open(xmlfilename, "wb") as xmlfile:
380 str_self = str(self)
381 if isinstance(str_self, str):
382 str_self = str_self.encode()
383 xmlfile.write(codecs.BOM_UTF16_LE + str_self)
384
385 def __str__(self) -> str:
386 """Convert the task to a string representation in XML format.
387
388 Returns:
389 str: The string representation of the task in XML format.
390 """
391 return (
392 universal_newlines(
393 f'<?xml version="1.0" encoding="UTF-16"?>\n{super().__str__()}'
394 )
395 .replace("\n", "\r\n")
396 .encode("UTF-16-LE")
397 )
398
399
400 class TaskScheduler:
401 """Task Scheduler interface.
402
403 Currently only implemented for Windows (Vista and up).
404 """
405
406 def __init__(self) -> None:
407 self.__ts = None
408 self.stdout = b""
409 self.lastreturncode = None
410
411 @property
412 def _ts(self) -> ITaskScheduler:
413 if not self.__ts:
414 import pythoncom
415 from win32com.taskscheduler.taskscheduler import (
416 CLSID_CTaskScheduler,
417 IID_ITaskScheduler,
418 )
419
420 self.__ts = pythoncom.CoCreateInstance(
421 CLSID_CTaskScheduler,
422 None,
423 pythoncom.CLSCTX_INPROC_SERVER,
424 IID_ITaskScheduler,
425 )
426 return self.__ts
427
428 def __contains__(self, name: str) -> bool:
429 """Check if task with given name exists.
430
431 Args:
432 name (str): The name of the task to check.
433
434 Returns:
435 bool: True if the task exists, False otherwise.
436 """
437 return f"{name}.job" in self._ts.Enum()
438
439 def __getitem__(self, name: str) -> Task:
440 """Get existing task by name.
441
442 Args:
443 name (str): The name of the task to retrieve.
444
445 Returns:
446 Task: The task object.
447 """
448 return self._ts.Activate(name)
449
450 def __iter__(self) -> Iterator:
451 """Iterate over task names.
452
453 Returns:
454 Iterator: An iterator over task names.
455 """
456 return iter(job[:-4] for job in self._ts.Enum())
457
458 def create_task(
459 self,
460 name: str,
461 author: str = "",
462 description: str = "",
463 group_id: str = "S-1-5-4",
464 run_level: str = RUNLEVEL_LEASTPRIVILEGE,
465 multiple_instances_policy: str = MULTIPLEINSTANCES_IGNORENEW,
466 disallow_start_if_on_batteries: bool = False,
467 stop_if_going_on_batteries: bool = False,
468 allow_hard_terminate: bool = True,
469 start_when_available: bool = False,
470 run_only_if_network_available: bool = False,
471 duration: None | str = None,
472 wait_timeout: None | int = None,
473 stop_on_idle_end: bool = False,
474 restart_on_idle: bool = False,
475 allow_start_on_demand: bool = True,
476 enabled: bool = True,
477 hidden: bool = False,
478 run_only_if_idle: bool = False,
479 wake_to_run: bool = False,
480 execution_time_limit: str = "PT72H",
481 priority: int = 5,
482 triggers: None | list[_Trigger] = None,
483 actions: None | list[ExecAction] = None,
484 replace_existing: bool = False,
485 elevated: bool = False,
486 echo: bool = False,
487 ) -> bool:
488 """Create a new task.
489
490 If replace_existing evaluates to True, delete any existing task with
491 same name first, otherwise raise KeyError.
492
493 Args:
494 name (str): The name of the task.
495 author (str): The author of the task.
496 description (str): The description of the task.
497 group_id (str): The group ID for the task.
498 run_level (str): The run level for the task.
499 multiple_instances_policy (str): The policy for multiple instances.
500 disallow_start_if_on_batteries (bool): Whether to disallow starting
501 the task if on batteries.
502 stop_if_going_on_batteries (bool): Whether to stop the task if
503 going on batteries.
504 allow_hard_terminate (bool): Whether to allow hard termination of
505 the task.
506 start_when_available (bool): Whether to start the task when
507 available.
508 run_only_if_network_available (bool): Whether to run the task only
509 if the network is available.
510 duration (str): The duration for which the task should run.
511 wait_timeout (str): The timeout for waiting for the task to finish.
512 stop_on_idle_end (bool): Whether to stop the task when the system
513 goes idle.
514 restart_on_idle (bool): Whether to restart the task when the system
515 goes idle.
516 allow_start_on_demand (bool): Whether to allow starting the task on
517 demand.
518 enabled (bool): Whether the task is enabled.
519 hidden (bool): Whether the task is hidden.
520 run_only_if_idle (bool): Whether to run the task only if the system
521 is idle.
522 wake_to_run (bool): Whether to wake the system to run the task.
523 execution_time_limit (str): The execution time limit for the task.
524 priority (int): The priority of the task.
525 triggers (list[Trigger]): List of triggers for this task, e.g.:
526 [LogonTrigger(), CalendarTrigger(), ResumeFromSleepTrigger()].
527 actions (list[Action]): List of actions for this task, e.g.:
528 [ExecAction("program.exe", ["arg1", "arg2"])].
529 replace_existing (bool): If True, replace an existing task with same
530 name, otherwise raise KeyError if it exists already.
531 elevated (bool): If True, run command with elevated privileges,
532 otherwise not. Note that this requires administrative privileges
533 and will prompt for elevation if necessary.
534 echo (bool): If True, print command
535 output to stdout, otherwise suppress it.
536
537 Raises:
538 KeyError: If replace_existing is False and a task with the same
539 name already exists.
540 pywintypes.error: If there is an error while creating the task.
541 OSError: If there is an error while writing the XML file or removing
542 temporary files.
543
544 Returns:
545 bool: True if the task was created successfully, False otherwise.
546 """
547 kwargs = {
548 "name": name,
549 "author": author,
550 "description": description,
551 "group_id": group_id,
552 "run_level": run_level,
553 "multiple_instances_policy": multiple_instances_policy,
554 "disallow_start_if_on_batteries": disallow_start_if_on_batteries,
555 "stop_if_going_on_batteries": stop_if_going_on_batteries,
556 "allow_hard_terminate": allow_hard_terminate,
557 "start_when_available": start_when_available,
558 "run_only_if_network_available": run_only_if_network_available,
559 "duration": duration,
560 "wait_timeout": wait_timeout,
561 "stop_on_idle_end": stop_on_idle_end,
562 "restart_on_idle": restart_on_idle,
563 "allow_start_on_demand": allow_start_on_demand,
564 "enabled": enabled,
565 "hidden": hidden,
566 "run_only_if_idle": run_only_if_idle,
567 "wake_to_run": wake_to_run,
568 "execution_time_limit": execution_time_limit,
569 "priority": priority,
570 "triggers": triggers,
571 "actions": actions,
572 }
573 if not replace_existing and name in self:
574 raise KeyError(f"The task {name} already exists!")
575
576 tempdir = tempfile.mkdtemp(prefix=f"{APPNAME}-")
577 task = Task(**kwargs)
578 xmlfilename = os.path.join(tempdir, f"{name}.xml")
579 task.write_xml(xmlfilename)
580 try:
581 return self._schtasks(
582 ["/Create", "/TN", name, "/XML", xmlfilename], elevated, echo
583 )
584 finally:
585 os.remove(xmlfilename)
586 os.rmdir(tempdir)
587
588 def create_logon_task(
589 self,
590 name: str,
591 cmd: str,
592 args: None | list[str] = None,
593 author: str = "",
594 description: str = "",
595 group_id: str = "S-1-5-4",
596 run_level: str = RUNLEVEL_LEASTPRIVILEGE,
597 multiple_instances_policy: str = MULTIPLEINSTANCES_IGNORENEW,
598 disallow_start_if_on_batteries: bool = False,
599 stop_if_going_on_batteries: bool = False,
600 allow_hard_terminate: bool = True,
601 start_when_available: bool = False,
602 run_only_if_network_available: bool = False,
603 duration: None | str = None,
604 wait_timeout: None | str = None,
605 stop_on_idle_end: bool = False,
606 restart_on_idle: bool = False,
607 allow_start_on_demand: bool = True,
608 enabled: bool = True,
609 hidden: bool = False,
610 run_only_if_idle: bool = False,
611 wake_to_run: bool = False,
612 execution_time_limit: str = "PT72H",
613 priority: int = 5,
614 replace_existing: bool = False,
615 elevated: bool = False,
616 echo: bool = False,
617 ) -> Task:
618 """Create a new task to be run under the current user account at logon.
619
620 Args:
621 name (str): The name of the task.
622 cmd (str): The command to run.
623 args (list[str]): The arguments to pass to the command.
624 author (str): The author of the task.
625 description (str): The description of the task.
626 group_id (str): The group ID for the task.
627 run_level (str): The run level for the task.
628 multiple_instances_policy (str): The policy for multiple instances.
629 disallow_start_if_on_batteries (bool): Whether to disallow starting
630 the task if on batteries.
631 stop_if_going_on_batteries (bool): Whether to stop the task if
632 going on batteries.
633 allow_hard_terminate (bool): Whether to allow hard termination of
634 the task.
635 start_when_available (bool): Whether to start the task when
636 available.
637 run_only_if_network_available (bool): Whether to run the task only
638 if the network is available.
639 duration (None | str): The duration for which the task should run.
640 wait_timeout (str): The timeout for waiting for the task to finish.
641 stop_on_idle_end (bool): Whether to stop the task when the system
642 goes idle.
643 restart_on_idle (bool): Whether to restart the task when the system
644 goes idle.
645 allow_start_on_demand (bool): Whether to allow starting the task on
646 demand.
647 enabled (bool): Whether the task is enabled.
648 hidden (bool): Whether the task is hidden.
649 run_only_if_idle (bool): Whether to run the task only if the system
650 is idle.
651 wake_to_run (bool): Whether to wake the system to run the task.
652 execution_time_limit (str): The execution time limit for the task.
653 priority (int): The priority of the task.
654 replace_existing (bool): Whether to replace an existing task with
655 the same name.
656 elevated (bool): Whether to run the command with elevated
657 privileges.
658 echo (bool): Whether to print the command output to stdout.
659
660 Returns:
661 Task: The created task object.
662 """
663 kwargs = {
664 "actions": [ExecAction(cmd, args)],
665 "allow_hard_terminate": allow_hard_terminate,
666 "allow_start_on_demand": allow_start_on_demand,
667 "author": author,
668 "description": description,
669 "disallow_start_if_on_batteries": disallow_start_if_on_batteries,
670 "duration": duration,
671 "echo": echo,
672 "elevated": elevated,
673 "enabled": enabled,
674 "execution_time_limit": execution_time_limit,
675 "group_id": group_id,
676 "hidden": hidden,
677 "multiple_instances_policy": multiple_instances_policy,
678 "name": name,
679 "priority": priority,
680 "replace_existing": replace_existing,
681 "restart_on_idle": restart_on_idle,
682 "run_level": run_level,
683 "run_only_if_idle": run_only_if_idle,
684 "run_only_if_network_available": run_only_if_network_available,
685 "start_when_available": start_when_available,
686 "stop_if_going_on_batteries": stop_if_going_on_batteries,
687 "stop_on_idle_end": stop_on_idle_end,
688 "triggers": [LogonTrigger()],
689 "wait_timeout": wait_timeout,
690 "wake_to_run": wake_to_run,
691 }
692 return self.create_task(**kwargs)
693
694 def delete(self, name: str) -> None:
695 """Delete existing task.
696
697 Args:
698 name (str): The name of the task to delete.
699 """
700 self._ts.Delete(name)
701
702 def disable(self, name: str, echo: bool = False) -> None:
703 """Disable (deactivate) existing task.
704
705 Args:
706 name (str): The name of the task to disable.
707 echo (bool): Whether to print the command output to stdout.
708 """
709 self._schtasks(["/Change", "/TN", name, "/DISABLE"], echo=echo)
710
711 def enable(self, name: str, echo: bool = False) -> None:
712 """Enable (activate) existing task.
713
714 Args:
715 name (str): The name of the task to enable.
716 echo (bool): Whether to print the command output to stdout.
717 """
718 self._schtasks(["/Change", "/TN", name, "/ENABLE"], echo=echo)
719
720 def get(self, name: str, default: None | Any = None) -> None | Task: # noqa: ANN401
721 """Get existing task.
722
723 Args:
724 name (str): The name of the task to retrieve.
725 default (None | Any): The value to return if the task does not
726 exist.
727
728 Returns:
729 None | Task: The task object if it exists, otherwise the default
730 value.
731 """
732 if name in self:
733 return self[name]
734 return default
735
736 def get_exit_code(self, task: Task) -> tuple[int, int]:
737 """Shorthand for task.GetExitCode().
738
739 Return a 2-tuple exitcode, startup_error_code.
740
741 Call win32api.FormatMessage() on either value to get a readable message
742
743 Returns:
744 tuple[int, int]: A tuple containing the exit code and startup error
745 code of the task.
746 """
747 return task.GetExitCode()
748
749 def items(self) -> list[tuple[str, Task]]:
750 """Iterate over existing tasks and their names.
751
752 Returns:
753 list[tuple[str, Task]]: A list of tuples containing task names and
754 their corresponding Task objects.
755 """
756 return list(zip(self, self.tasks()))
757
758 def iteritems(self) -> Iterator[tuple[str, Task]]:
759 """Iterate over existing tasks and their names.
760
761 Returns:
762 Iterator[tuple[str, Task]]: An iterator over tuples containing task
763 names and their corresponding Task objects.
764 """
765 return zip(self, self.itertasks())
766
767 def itertasks(self) -> Iterator[Task]:
768 """Iterate over existing tasks.
769
770 Returns:
771 Iterator[Task]: An iterator over Task objects representing existing
772 tasks.
773 """
774 return map(self.get, self)
775
776 def run(self, name: str, elevated: bool = False, echo: bool = False) -> bool:
777 """Run existing task.
778
779 Args:
780 name (str): The name of the task to run.
781 elevated (bool): Whether to run the command with elevated privileges.
782 echo (bool): Whether to print the command output to stdout.
783
784 Returns:
785 bool: True if the task was successfully run, False otherwise.
786 """
787 return self._schtasks(["/Run", "/TN", name], elevated, echo)
788
789 def has_task(self, name: str) -> bool:
790 """Same as name in self.
791
792 Args:
793 name (str): The name of the task to check.
794
795 Returns:
796 bool: True if the task exists, False otherwise.
797 """
798 return name in self
799
800 def query_task(self, name: str, echo: bool = False) -> bool:
801 """Query task.
802
803 Args:
804 name (str): The name of the task to query.
805 echo (bool, optional): Whether to print the command output to
806 stdout. Default is False.
807
808 Returns:
809 bool: True if the task exists, False otherwise.
810 """
811 return self._schtasks(["/Query", "/TN", name], False, echo)
812
813 def _schtasks(
814 self, args: list[str], elevated: bool = False, echo: bool = False
815 ) -> bool:
816 """Run schtasks.exe with the given arguments.
817
818 Args:
819 args (list[str]): The arguments to pass to schtasks.exe.
820 elevated (bool): Whether to run the command with elevated privileges.
821 echo (bool): Whether to print the command output to stdout.
822
823 Returns:
824 bool: True if the command was successful, False otherwise.
825 """
826 if elevated:
827 try:
828 p = run_as_admin("schtasks.exe", args, close_process=False, show=False)
829 except pywintypes.error as exception:
830 if exception.args[0] == winerror.ERROR_CANCELLED:
831 self.lastreturncode = winerror.ERROR_CANCELLED
832 else:
833 raise
834 else:
835 self.lastreturncode = int(p["hProcess"].handle == 0)
836 p["hProcess"].Close()
837 finally:
838 self.stdout = b""
839 else:
840 args.insert(0, "schtasks.exe")
841 startupinfo = sp.STARTUPINFO()
842 startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW
843 startupinfo.wShowWindow = sp.SW_HIDE
844 p = sp.Popen(
845 [str(arg) for arg in args],
846 stdin=sp.PIPE,
847 stdout=sp.PIPE,
848 stderr=sp.STDOUT,
849 startupinfo=startupinfo,
850 )
851 self.stdout, _ = p.communicate()
852 if echo:
853 print(str(self.stdout, encoding=ENC, errors="replace"))
854 self.lastreturncode = p.returncode
855 return self.lastreturncode == 0
856
857 def tasks(self) -> list[Task]:
858 """Get existing tasks.
859
860 Returns:
861 list[Task]: A list of Task objects representing existing tasks.
862 """
863 return list(map(self.get, self))
864
865
866 if __name__ == "__main__":
867
868 def print_task_attr(name: str, attr: Any, *args: list[Any]) -> None: # noqa: ANN401
869 """Print task attribute.
870
871 Args:
872 name (str): The name of the attribute.
873 attr (Any): The attribute value.
874 *args: Additional arguments to pass to the attribute if it is
875 callable.
876 """
877 print(f"{name:18s}:", end=" ")
878 if callable(attr):
879 try:
880 print(attr(*args))
881 except pywintypes.com_error as exception:
882 print(OSError(*exception.args))
883 except TypeError as exception:
884 print(exception)
885 else:
886 print(attr)
887
888 ts = TaskScheduler()
889
890 for taskname in ts:
891 task = ts[taskname]
892 print("=" * 79)
893 print("{:18s}:".format("Task"), taskname)
894 for name in dir(task):
895 if name == "GetRunTimes":
896 continue
897 attr = getattr(task, name)
898 if name.startswith("Get"):
899 if name in ("GetTrigger", "GetTriggerString"):
900 for i in range(task.GetTriggerCount()):
901 print_task_attr(f"{name[3:]}({i:d})", attr, i)
902 else:
903 print_task_attr(name[3:], attr)