Skip to content

Wrapper

Subprocess wrappers for external command-line tools.

Quick reference

Symbol Summary Preferred for
Tool The core every engine and wrapper shares: settings → environment → executable → env vars → timeout → logger; command, run_command, check_executable Subclassing through Wrapper or Engine
ToolError The one failure: tool, returncode, tail (stderr, stdout or log) Catching a failed, missing or timed-out tool
Wrapper Base: settings from [wrapper.<tool>], logged subprocess runs, check=True by default Writing a wrapper for another program
AntechamberWrapper AMBER antechamber (type + charge assignment) GAFF atom typing
Parmchk2Wrapper AMBER parmchk2 (missing parameter generation) Force field completion
TleapWrapper AMBER tleap (topology building) System assembly
PrepgenWrapper AMBER prepgen (residue template generation) Polymer residues
SanderWrapper AMBER sander: run_from_mdin(mdin_text, prmtop, inpcrd) Running a caller's mdin on a prmtop/inpcrd
EnvironmentSpec The conda / venv a tool runs in, resolved from its settings Inspecting or building a command prefix
run_step run_step(tool, output, call): run one step, require the file it must write; raises ToolError with the tool's output Chaining tools in a pipeline

Canonical example

# docs: skip — needs AmberTools
from molpy.config import load_config
from molpy.wrapper import TleapWrapper

config = load_config({"wrapper": {"env": "AmberTools25", "env_manager": "conda"}})
leap = TleapWrapper("leap_work", config=config)
result = leap.run_from_script("source leaprc.gaff2\nquit\n")
print(result.returncode)  # 0

Key behavior

  • A wrapper's executable, environment (env + env_manager), env_vars and timeout are its [wrapper.<tool>] settings in molpy's configuration, falling back to [wrapper] (molpy.config); the constructor takes the working directory and, optionally, the config
  • Environment isolation is owned by EnvironmentSpec; no auto-detection of manager type. env and env_manager are set together, or both omitted for the system PATH; managers are conda and venv (one spelling each)
  • Safe to instantiate even if the executable is missing (check_executable() raises, is_available() reports it; run_step refuses to start). The lookup runs once per instance; a conda lookup (conda run … which) is logged at DEBUG and time-limited
  • Every failure is a ToolError (a RuntimeError) carrying tool ("wrapper.tleap"), returncode and tail: a missing executable, a program that cannot start, a timeout, a non-zero exit (check=True is the default; check=False returns the CompletedProcess) or, in run_step, a missing output
  • A third-party wrapper subclasses Wrapper, names its table in tool and reads [wrapper.<tool>] like the built-in ones (Adding a Wrapper)
  • Every run is logged to molpy.wrapper.<tool> as mollog records (process started / finished / failed / timed out) carrying the command, cwd, returncode and elapsed_s

Full API

Environment

EnvironmentSpec dataclass

EnvironmentSpec(
    env=None, env_manager=None, conda_executable="conda"
)

Validated subprocess environment isolation.

Construct via :meth:resolve (or :meth:system). After resolve:

  • system — both fields None
  • conda name — env: str, env_manager: "conda"
  • conda prefix / venv — env: Path, env_manager: "conda"|"venv"

conda_executable is the conda that conda run invokes. :meth:resolve_executable remembers each answer for the life of the instance (each engine and wrapper resolves its own).

is_system property

is_system

True when no isolation is configured.

command_prefix

command_prefix(*, no_capture_output=False)

Return an argv prefix for the configured manager, or [].

For conda this is [conda, run, (-n|-p), <env>]. For venv / system the prefix is empty (isolation is via :meth:merge_environ). Path prefixes are emitted as str(path) for the OS.

Parameters:

Name Type Description Default
no_capture_output bool

When True, insert --no-capture-output after run (useful for engines that stream logs).

False

merge_environ

merge_environ(base=None, extra=None)

Build a subprocess environment dict.

Merge order (later wins): base (default os.environ) → venv PATH / VIRTUAL_ENV injection when applicable → extra.

resolve classmethod

resolve(
    env=None, env_manager=None, *, conda_executable="conda"
)

Validate and normalise user env / env_manager input.

Both must be set together, or both omitted for the system environment. Manager type is never inferred from env. Path-like values are stored as :class:~pathlib.Path.

Parameters:

Name Type Description Default
env str | Path | None

Conda env name / prefix, or venv prefix (str | Path).

None
env_manager str | None

"conda" or "venv".

None
conda_executable str

The conda that conda run invokes.

'conda'

Returns:

Type Description
EnvironmentSpec

A frozen :class:EnvironmentSpec.

Raises:

Type Description
ValueError

If exactly one of the pair is set, or the manager string is unsupported.

resolve_executable

resolve_executable(exe, *, logger=None)

Best-effort absolute path for exe inside this environment.

exe may be path-like at the public boundary; filesystem paths are converted to :class:~pathlib.Path immediately. A conda env is asked with conda run … which through :func:~molpy.wrapper._process.run_process (logged at DEBUG to logger, killed after :data:RESOLVE_TIMEOUT seconds). Each answer is remembered by this instance.

Parameters:

Name Type Description Default
exe str | Path

A program name or a path.

required
logger Logger | None

Where the conda lookup logs; None is molpy.wrapper.environment.

None

Returns:

Type Description
str | None

A str suitable for subprocess argv, or None if not found

str | None

(or the lookup could not run).

system classmethod

system()

No isolation — use the current process environment.

Base

Tool

Tool(workdir=None, *, config=None)

An external program resolved from molpy's configuration.

Subclasses set :attr:group (the base class does: "engine" or "wrapper") and :attr:tool, the name of the configuration table ([<group>.<tool>], falling back to [<group>]).

Parameters:

Name Type Description Default
workdir str | Path | None

Where the tool runs; None lets the subclass decide.

None
config Config | None

molpy's configuration (:func:molpy.config.load_config); None loads it (package defaults, user and project files).

None

Attributes:

Name Type Description
settings

The resolved :class:~molpy.config.ToolSettings.

environment

The :class:EnvironmentSpec the tool runs in.

logger

The tool's logger, molpy.<group>.<tool>.

executable str

The program to run (settings.executable, else :meth:_default_executable).

workdir

Where the tool runs, or None.

launcher list[str]

MPI / scheduler prefix before the executable (engines; empty for wrappers).

env_vars dict[str, str]

Environment variables set for the subprocess.

timeout

Seconds before a subprocess is killed (None: no limit).

Raises:

Type Description
KeyError

:attr:group is not a configured group.

ValueError

The configured environment is incomplete or its manager unsupported, or no executable is configured and the tool has no default.

key property

key

The settings table, "<group>.<tool>" ("engine.lammps").

check_executable

check_executable()

The executable's resolved path.

Raises:

Type Description
ToolError

The executable is not found; the message names the settings to fix.

command

command(args=(), *, launch=True)

The full argv: [env prefix] [launcher] executable args.

The env prefix is :meth:EnvironmentSpec.command_prefix (conda's conda run --no-capture-output -n <env>; empty for venv and the system, which act through the environment variables).

Parameters:

Name Type Description Default
args Sequence[str]

What follows the executable.

()
launch bool

Put :attr:launcher before the executable (False for a serial step such as GROMACS's grompp).

True

is_available

is_available()

True when the executable can be found in the environment.

resolve_executable

resolve_executable()

The executable's absolute path in the environment, or None.

Looked up once per instance (:meth:EnvironmentSpec.resolve_executable).

run_command

run_command(
    command,
    *,
    cwd,
    capture_output,
    check=True,
    input_text=None,
    log=None,
    **fields,
)

Start command in cwd with the tool's environment and time limit.

The run is logged to :attr:logger (process started / finished / failed / timed out), each record carrying the command, the directory and fields (e.g. step="mdrun").

Parameters:

Name Type Description Default
command Sequence[str]

The full argv (usually :meth:command).

required
cwd str | Path | None

Working directory; None is the caller's.

required
capture_output bool

Capture stdout / stderr.

required
check bool

Raise :class:ToolError on a non-zero exit.

True
input_text str | None

Text sent to stdin.

None
log Path | None

The program's log file, the error's tail when nothing was captured.

None
**fields Any

Extra structured fields on every record.

{}

Raises:

Type Description
ToolError

The program could not start, timed out, or (with check) exited non-zero.

ToolError

ToolError(tool, reason, *, returncode=None, tail='')

Bases: RuntimeError

An external tool failed.

It is missing, could not start, timed out, exited non-zero, or left an output it must write unwritten.

Attributes:

Name Type Description
tool

The tool's settings table, "<group>.<name>" ("engine.lammps", "wrapper.tleap").

reason

What went wrong, in one line.

returncode

The exit status; None when the program never exited on its own (missing, not started, timed out).

tail

The last lines of its stderr, its stdout, or its log file (whichever is the first non-empty); "" when none was kept.

Wrapper

Wrapper(workdir=None, *, config=None)

Bases: Tool

Minimal base class for external tool wrappers.

A subclass names its configuration table in :attr:tool ("tleap" reads [wrapper.tleap], falling back to [wrapper]). Settings, environment, executable, logger and the failure contract come from :class:~molpy.wrapper.Tool.

Parameters:

Name Type Description Default
workdir str | Path | None

Where the tool runs; None is the caller's directory.

None
config Config | None

molpy's configuration (:func:molpy.config.load_config); None loads it (package defaults, user and project files).

None

Raises:

Type Description
ValueError

The configured environment is incomplete or its manager unsupported, or no executable is configured.

run

run(
    args=(),
    *,
    input_text=None,
    capture_output=True,
    check=True,
)

Execute the wrapper's command in :attr:workdir.

Parameters:

Name Type Description Default
args Sequence[str]

Command-line arguments (without the executable).

()
input_text str | None

Text to send to stdin.

None
capture_output bool

Whether to capture stdout/stderr.

True
check bool

Raise :class:~molpy.wrapper.ToolError on a non-zero exit.

True

Returns:

Type Description
CompletedProcess[str]

The completed process result.

Raises:

Type Description
ToolError

The tool could not start, timed out, or (with check) exited non-zero.

run_step

run_step(tool, output, call)

Run one tool step and require the file it must write.

Parameters:

Name Type Description Default
tool Tool

The tool call runs; checked for its executable first.

required
output Path

The file the step must leave behind.

required
call Callable[[], CompletedProcess[str]]

Runs the step (typically a bound wrapper method in a lambda).

required

Returns:

Type Description
CompletedProcess[str]

The completed process.

Raises:

Type Description
ToolError

The executable is missing, the step fails, or it exits 0 but leaves output unwritten. The error carries the tool's stderr, or its stdout when stderr is empty (tleap and prepgen report there).

Antechamber

AntechamberWrapper

AntechamberWrapper(workdir=None, *, config=None)

Bases: Wrapper

Wrapper for the 'antechamber' CLI.

atomtype_assign

atomtype_assign(
    input_file,
    output_file,
    *,
    parameter_set,
    input_format="pdb",
    output_format="mol2",
    charge_method="bcc",
    net_charge=0,
    formal_charges=False,
    check=True,
)

Perform atom type assignment and charge calculation.

This is the primary workflow for preparing ligands with antechamber: assigning GAFF atom types and computing partial charges.

Parameters:

Name Type Description Default
input_file str | Path

Input structure file.

required
output_file str | Path

Output structure file (with assigned atom types and charges).

required
parameter_set Literal['gaff', 'gaff2', 'amber', 'bcc', 'abcg2', 'sybyl']

The atom-type table (-at), molrs's parameter_set (:class:molpy.ff.typifier.AtdTypifier): gaff, gaff2, amber, bcc, abcg2 or sybyl. Required, as in molrs.

required
input_format Literal['pdb', 'mol2', 'ac']

Input file format.

'pdb'
output_format Literal['mol2', 'ac']

Output file format.

'mol2'
charge_method Literal['gas', 'bcc', 'abcg2', 'mul', 'be3', 'cm2', 'esp']

Method for charge calculation (gas: Gasteiger; bcc / abcg2: AM1-BCC / ABCG2; mul: sqm's AM1 Mulliken charges, unequivalenced; etc.).

'bcc'
net_charge int

Net charge of the molecule.

0
formal_charges bool

If True, use formal charges instead of computing them.

False
check bool

Raise :class:~molpy.wrapper.ToolError on a non-zero exit.

True

Returns:

Type Description
CompletedProcess[str]

The completed process result.

Prepgen

PrepgenWrapper

PrepgenWrapper(workdir=None, *, config=None)

Bases: Wrapper

Wrapper for the 'prepgen' CLI.

Prepgen generates AMBER residue templates (.prepi files) with connection points defined by control files specifying HEAD_NAME, TAIL_NAME, etc.

Example

wrapper = PrepgenWrapper("./work") wrapper.generate_residue( ... input_file="mol.ac", ... output_file="mol.prepi", ... control_file="mol.chain", ... residue_name="MOL", ... )

generate_residue

generate_residue(
    input_file,
    output_file,
    control_file,
    residue_name,
    *,
    output_format="prepi",
    check=True,
)

Generate a residue template with connection points.

Parameters:

Name Type Description Default
input_file str | Path

Input structure file (.ac format from antechamber).

required
output_file str | Path

Output residue template file (.prepi).

required
control_file str | Path

Control file specifying HEAD_NAME, TAIL_NAME, OMIT_NAME.

required
residue_name str

Name for the residue (max 4 chars recommended).

required
output_format Literal['prepi', 'prepc']

Output format (prepi or prepc).

'prepi'
check bool

Raise :class:~molpy.wrapper.ToolError on a non-zero exit.

True

Returns:

Type Description
CompletedProcess[str]

The completed process result.

Example control file content

HEAD_NAME C1 TAIL_NAME O5 OMIT_NAME H1 OMIT_NAME H2 PRE_HEAD_TYPE c3 POST_TAIL_TYPE os CHARGE 0

Parmchk2Wrapper

Parmchk2Wrapper(workdir=None, *, config=None)

Bases: Wrapper

Wrapper for the 'parmchk2' tool.

generate_parameters

generate_parameters(
    input_file,
    output_file,
    *,
    parameter_set,
    input_format="mol2",
    check=True,
)

Check and generate missing force field parameters.

This is the primary workflow: read atom types and bonds from antechamber output, check against force field parameters, and generate missing ones.

Parameters:

Name Type Description Default
input_file str | Path

Input structure file (mol2 or ac format, typically from antechamber).

required
output_file str | Path

Output AMBER parameter file (frcmod format).

required
input_format Literal['mol2', 'ac', 'mol', 'pdb']

Input file format (mol2, ac, mol, pdb).

'mol2'
parameter_set Literal['gaff', 'gaff2']

The GAFF generation whose parameters are checked (-s), molrs's parameter_set: "gaff" or "gaff2". Required, as in molrs.

required
check bool

Raise :class:~molpy.wrapper.ToolError on a non-zero exit.

True

Returns:

Type Description
CompletedProcess[str]

The completed process result.

TLeap

TleapWrapper

TleapWrapper(workdir=None, *, config=None)

Bases: Wrapper

Wrapper for the 'tleap' binary ([wrapper.tleap]).

run_from_script

run_from_script(
    script_text, *, script_name="tleap.in", check=True
)

Execute tleap from a script text.

Parameters:

Name Type Description Default
script_text str

The tleap script content.

required
script_name str

Name of the script file to create (in workdir).

'tleap.in'
check bool

Raise :class:~molpy.wrapper.ToolError on a non-zero exit.

True

Returns:

Type Description
CompletedProcess[str]

The completed process result.

Raises:

Type Description
ValueError

If no workdir is set.

ToolError

tleap failed (with check).

Sander

SanderWrapper

SanderWrapper(workdir=None, *, config=None)

Bases: Wrapper

Wrapper for the 'sander' binary ([wrapper.sander]).

run_from_mdin

run_from_mdin(
    mdin_text, prmtop, inpcrd, *, name="sander", check=True
)

Write <name>.in and run sander on it.

Runs sander -O -i <name>.in -p <prmtop> -c <inpcrd> -r <name>.rst -o <name>.out in :attr:workdir; the restart <name>.rst and the output <name>.out land there.

Parameters:

Name Type Description Default
mdin_text str

The mdin control text (a &cntrl namelist).

required
prmtop str | Path

The topology.

required
inpcrd str | Path

The starting coordinates.

required
name str

Stem of the control, restart and output files.

'sander'
check bool

Raise :class:~molpy.wrapper.ToolError on a non-zero exit.

True

Returns:

Type Description
CompletedProcess[str]

The completed process result.

Raises:

Type Description
ValueError

If no workdir is set.

ToolError

sander failed (with check).