Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_python_runner.py

raw
1 # Copyright (c) 2024, Alexei Znamensky <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import os
11 import typing as t
12
13 from ansible_collections.community.general.plugins.module_utils._cmd_runner import CmdRunner, _ensure_list
14
15 if t.TYPE_CHECKING:
16 from ansible.module_utils.basic import AnsibleModule
17
18
19 class PythonRunner(CmdRunner):
20 def __init__(
21 self,
22 module: AnsibleModule,
23 command,
24 arg_formats=None,
25 default_args_order=(),
26 check_rc: bool = False,
27 force_lang: str = "C",
28 path_prefix: list[str] | None = None,
29 environ_update: dict[str, str] | None = None,
30 python: str = "python",
31 venv: str | None = None,
32 ) -> None:
33 self.python = python
34 self.venv = venv
35 self.has_venv = venv is not None
36
37 if os.path.isabs(python) or "/" in python:
38 self.python = python
39 elif venv is not None:
40 if path_prefix is None:
41 path_prefix = []
42 path_prefix.append(os.path.join(venv, "bin"))
43 if environ_update is None:
44 environ_update = {}
45 environ_update["PATH"] = f"{':'.join(path_prefix)}:{os.environ['PATH']}"
46 environ_update["VIRTUAL_ENV"] = venv
47
48 python_cmd = [self.python] + _ensure_list(command)
49
50 super().__init__(
51 module, python_cmd, arg_formats, default_args_order, check_rc, force_lang, path_prefix, environ_update
52 )