[pp:python] add '"mode": "eval"'

This commit is contained in:
Mike Fährmann
2025-09-22 16:54:50 +02:00
parent b49745d351
commit 2480ba2a55
3 changed files with 56 additions and 6 deletions

View File

@@ -8017,6 +8017,23 @@ Description
See `metadata.event`_ for a list of available events.
python.expression
-----------------
Type
``string``
Example
* ``"print('Foo Bar')"``
* ``"terminate()"``
Description
A
`Python expression <https://docs.python.org/3/glossary.html#term-expression>`__
to
`evaluate <https://docs.python.org/3/library/functions.html#eval>`__.
Note: Only used with
`"mode": "eval" <python.mode_>`__
python.function
---------------
Type
@@ -8034,6 +8051,23 @@ Description
It gets called with the current metadata dict as argument.
python.mode
-----------
Type
``string``
Default
``"function"``
Description
Selects what Python code to run.
``"eval"``
Evaluate an
`expression <python.expression_>`__
``function"``
Call a
`function <python.function_>`__
rename.from
-----------
Type

View File

@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Copyright 2023 Mike Fährmann
# Copyright 2023-2025 Mike Fährmann
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
@@ -17,10 +17,14 @@ class PythonPP(PostProcessor):
def __init__(self, job, options):
PostProcessor.__init__(self, job)
spec = options["function"]
module_name, _, function_name = spec.rpartition(":")
module = util.import_file(module_name)
self.function = getattr(module, function_name)
mode = options.get("mode")
if mode == "eval" or not mode and options.get("expression"):
self.function = util.compile_expression(options["expression"])
else:
spec = options["function"]
module_name, _, function_name = spec.rpartition(":")
module = util.import_file(module_name)
self.function = getattr(module, function_name)
events = options.get("event")
if events is None:

View File

@@ -20,7 +20,7 @@ import collections
from datetime import datetime
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from gallery_dl import extractor, output, path, util # noqa E402
from gallery_dl import extractor, output, path, util, exception # noqa E402
from gallery_dl import postprocessor, config # noqa E402
from gallery_dl.postprocessor.common import PostProcessor # noqa E402
@@ -867,6 +867,18 @@ class PythonTest(BasePostprocessorTest):
self._trigger()
self.assertEqual(self.pathfmt.kwdict["_result"], 24)
def test_eval(self):
self._create({"mode": "eval", "expression": "abort()"})
with self.assertRaises(exception.StopExtraction):
self._trigger()
def test_eval_auto(self):
self._create({"expression": "abort()"})
with self.assertRaises(exception.StopExtraction):
self._trigger()
def _write_module(self, path):
with open(path, "w") as fp:
fp.write("""