| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright 2023-2025 Mike Fährmann |
| 4 |
# |
| 5 |
# This program is free software; you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU General Public License version 2 as |
| 7 |
# published by the Free Software Foundation. |
| 8 |
|
| 9 |
"""Run Python functions""" |
| 10 |
|
| 11 |
from .common import PostProcessor |
| 12 |
from .. import util |
| 13 |
|
| 14 |
|
| 15 |
class PythonPP(PostProcessor): |
| 16 |
|
| 17 |
def __init__(self, job, options): |
| 18 |
PostProcessor.__init__(self, job) |
| 19 |
|
| 20 |
mode = options.get("mode") |
| 21 |
if mode == "eval" or not mode and options.get("expression"): |
| 22 |
self.function = util.compile_expression(options["expression"]) |
| 23 |
else: |
| 24 |
spec = options["function"] |
| 25 |
module_name, _, function_name = spec.rpartition(":") |
| 26 |
module = util.import_file(module_name) |
| 27 |
self.function = getattr(module, function_name) |
| 28 |
|
| 29 |
if archive := self._archive_init(job, options): |
| 30 |
self.run = self.run_archive |
| 31 |
|
| 32 |
events = options.get("event") |
| 33 |
if events is None: |
| 34 |
events = ("file",) |
| 35 |
elif isinstance(events, str): |
| 36 |
events = events.split(",") |
| 37 |
job.register_hooks({event: self.run for event in events}, options) |
| 38 |
|
| 39 |
if archive: |
| 40 |
self._archive_register(job) |
| 41 |
|
| 42 |
def run(self, pathfmt): |
| 43 |
self.function(pathfmt.kwdict) |
| 44 |
|
| 45 |
def run_archive(self, pathfmt): |
| 46 |
kwdict = pathfmt.kwdict |
| 47 |
if self.archive.check(kwdict): |
| 48 |
return |
| 49 |
self.function(kwdict) |
| 50 |
self.archive.add(kwdict) |
| 51 |
|
| 52 |
|
| 53 |
__postprocessor__ = PythonPP |