Skip to content

Commit 10cdf5f

Browse files
committed
Add functions for finding and running muse2
1 parent 50f8ab6 commit 10cdf5f

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

muse2_data_analysis/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,7 @@
33
from contextlib import suppress
44
from importlib.metadata import PackageNotFoundError, version
55

6+
from .muse2 import find_muse2, run_muse2 # noqa: F401
7+
68
with suppress(PackageNotFoundError):
79
__version__ = version(__name__)

muse2_data_analysis/muse2.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""Tools for running the muse2 command-line program.
2+
3+
If the MUSE2_PATH environment variable is set, this will be used, otherwise muse2 will
4+
be searched for on the PATH.
5+
"""
6+
7+
import os
8+
import shutil
9+
import subprocess as sp
10+
from pathlib import Path
11+
12+
_muse2_path: Path | None = None
13+
14+
15+
def find_muse2() -> Path:
16+
"""Get the path to muse2, if any.
17+
18+
Raises an exception if muse2 is not found.
19+
"""
20+
# Cache path
21+
global _muse2_path
22+
if _muse2_path:
23+
return _muse2_path
24+
25+
path = os.getenv("MUSE2_PATH") or shutil.which("muse2")
26+
if not path:
27+
raise RuntimeError(
28+
"Could not find path to muse2. Either set the MUSE2_PATH environment "
29+
"variable or installing muse2 to your PATH (e.g. by running 'cargo "
30+
"install muse2')"
31+
)
32+
33+
_muse2_path = Path(path)
34+
return _muse2_path
35+
36+
37+
def run_muse2(*args: str) -> str:
38+
"""Run muse2 with the specified arguments, returning combined stdout and stderr.
39+
40+
Raises an exception if muse2 is not found.
41+
"""
42+
muse2 = find_muse2()
43+
output = sp.run((muse2, *args), text=True, stdout=sp.PIPE, stderr=sp.STDOUT)
44+
if output.returncode != 0:
45+
raise RuntimeError(f"Error running muse2: {output.stdout}")
46+
47+
return output.stdout

0 commit comments

Comments
 (0)