eq36 0.2.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
eq36/__init__.py ADDED
@@ -0,0 +1,266 @@
1
+ """Provide EQ3/6 binaries and utilities for calling them from Python."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from enum import IntEnum
7
+ from subprocess import PIPE, Popen, TimeoutExpired
8
+ from typing import TYPE_CHECKING
9
+
10
+ from typing_extensions import assert_never, override
11
+
12
+ from eq36.paths import get_execpath
13
+
14
+ if TYPE_CHECKING:
15
+ from pathlib import Path
16
+
17
+
18
+ class RunCode(IntEnum):
19
+ """A code to represent the execution status (exit code) of an EQ3/6 call."""
20
+
21
+ ## The command completed without an apparent error.
22
+ SUCCESS = 0
23
+ ## An error occurred while running EQPT
24
+ EQPT_ERROR = 20
25
+ ## An error occurred while running EQ3
26
+ EQ3_ERROR = 30
27
+ ## An error occurred while running EQ6
28
+ EQ6_ERROR = 60
29
+ ## The command timed out
30
+ TIMEOUT = 90
31
+
32
+ def __str__(self) -> str:
33
+ """
34
+ Format a `RunCode` as a string for error messages.
35
+
36
+ @return A human-readable description of the code
37
+ """
38
+ match self:
39
+ case RunCode.SUCCESS:
40
+ return "success"
41
+ case RunCode.EQPT_ERROR:
42
+ return "eqpt failed with an error"
43
+ case RunCode.EQ3_ERROR:
44
+ return "eq3 failed with an error"
45
+ case RunCode.EQ6_ERROR:
46
+ return "eq6 failed with an error"
47
+ case RunCode.TIMEOUT:
48
+ return "command timed out"
49
+ case _:
50
+ assert_never(self)
51
+
52
+
53
+ class Eq36Error(Exception):
54
+ """
55
+ An error specific to running EQ3/6 binaries.
56
+
57
+ @todo Consider introducing an exception hierarchy, rooted at `Eq36Error`,
58
+ in lieu of distinguishing errors by `RunCode`, e.g. subclasses for
59
+ errors in `eqpt`, `eq3nr` and `eq6`, and for timeouts. The hierarchy
60
+ could also include errors not specific to running the binaries, such
61
+ as a `Data1Error` for invalid data1 files (see `ERRORS.md`).
62
+ """
63
+
64
+ ## The code identifying the error, either a `RunCode` or a process exit code
65
+ code: RunCode | int
66
+
67
+ def __init__(self, *args: object, code: RunCode | int | None = None) -> None:
68
+ """
69
+ Construct an `Eq36Error` from `args` and a `code`.
70
+
71
+ @param args Positional arguments passed on to `Exception`; the first, if
72
+ provided, is used as the error message
73
+ @param code An optional (keyword-only) code identifying the error;
74
+ defaults to `1`
75
+ """
76
+ super().__init__(*args)
77
+ self.code = code if code is not None else 1
78
+
79
+ @override
80
+ def __str__(self) -> str:
81
+ """
82
+ Render the error as a string.
83
+
84
+ If the error is initialized with a message, that is returned. Otherwise
85
+ the code is used to generate an error message: known `RunCode` values
86
+ are rendered via `RunCode.__str__`, and any other code is reported as
87
+ an unknown error.
88
+
89
+ @return The error message
90
+ """
91
+ if self.args:
92
+ return str(self.args[0])
93
+
94
+ if isinstance(self.code, IntEnum):
95
+ return str(self.code)
96
+
97
+ try:
98
+ return str(RunCode(self.code))
99
+ except ValueError:
100
+ return f"failed with an unknown error (code: {self.code})"
101
+
102
+
103
+ def _error_guard(output: bytes | str, cmd: str, code: RunCode | int | None, fname: str | Path | None = None) -> None:
104
+ """
105
+ Raise an informative error if one is found in the output of a command.
106
+
107
+ The output is searched for EQ3/6 error messages, i.e. those beginning with
108
+ `"Error - "`. An `Eq36Error` is raised for the first non-empty message, with
109
+ the `"Error"` prefix replaced by `cmd`.
110
+
111
+ @private
112
+
113
+ @param output The output (`stdout`) of the command
114
+ @param cmd The command that was run
115
+ @param code An optional code to use if an error is encountered
116
+ @param fname An optional filename to include in any error message
117
+
118
+ @throws Eq36Error if an error message is found in the command output
119
+ """
120
+ if isinstance(output, bytes):
121
+ output = output.decode("utf-8", errors="replace")
122
+
123
+ matches = re.finditer(r"Error - (.*?)(?:\n\s*\n|\Z)", output, flags=re.DOTALL)
124
+ for match in matches:
125
+ error_msg = " ".join(match.group(1).split())
126
+ if error_msg:
127
+ msg = f"{cmd} - {error_msg}"
128
+ if fname is not None:
129
+ msg += f" in file {str(fname)!r}"
130
+ raise Eq36Error(msg, code=code)
131
+
132
+
133
+ def _run(
134
+ cmd: str | Path,
135
+ *args: str,
136
+ timeout: float | None = None,
137
+ code: RunCode | int | None = None,
138
+ fname: str | Path | None = None,
139
+ error_check: bool = True,
140
+ ) -> tuple[bytes, bytes]:
141
+ """
142
+ Run an EQ3/6 command and return the `stdout` and `stderr` output.
143
+
144
+ @private
145
+
146
+ @param cmd The filepath of the command to run
147
+ @param args Arguments to pass to the command
148
+ @param timeout An optional timeout for the command (in seconds)
149
+ @param code An optional error code to use if an error is found in `stdout`
150
+ @param fname An optional filename to include in any generated error messages
151
+ @param error_check Whether or not to check `stdout` for error messages
152
+
153
+ @return A tuple of the `stdout` and `stderr` output of the command
154
+
155
+ @throws Eq36Error with `code` if `stdout` includes an error message and `error_check == True`
156
+ @throws Eq36Error with the process' exit code if the command exits with a non-zero exit code (e.g. segfaults)
157
+ @throws Eq36Error with `RunCode.TIMEOUT` if the command times out
158
+ @throws OSError if the command cannot be executed
159
+ """
160
+ process = Popen([cmd, *args], stdout=PIPE, stderr=PIPE)
161
+ try:
162
+ stdout, stderr = process.communicate(timeout=timeout)
163
+ if error_check:
164
+ _error_guard(stdout, str(cmd), code=code, fname=fname)
165
+ except TimeoutExpired as terr:
166
+ process.kill()
167
+ stdout, stderr = process.communicate()
168
+ if error_check:
169
+ try:
170
+ _error_guard(stdout, str(cmd), code=code, fname=fname)
171
+ msg = f"{cmd} timed out without errors"
172
+ if fname is not None:
173
+ msg += f" in file {fname!r}"
174
+ except Eq36Error as e:
175
+ msg = f"{cmd} timed out with errors"
176
+ if fname is not None:
177
+ msg += f" in file {fname!r}"
178
+ raise Eq36Error(msg, code=RunCode.TIMEOUT) from e
179
+
180
+ raise Eq36Error(msg, code=RunCode.TIMEOUT) from terr
181
+
182
+ msg = f"{cmd} timed out"
183
+ if fname is not None:
184
+ msg += f" on file {fname!r}"
185
+ raise Eq36Error(msg, code=RunCode.TIMEOUT) from terr
186
+
187
+ if process.returncode != 0:
188
+ raise Eq36Error(code=process.returncode)
189
+
190
+ return stdout, stderr
191
+
192
+
193
+ def eqpt(data0: str | Path, timeout: float | None = None, error_check: bool = True) -> tuple[bytes, bytes]:
194
+ """
195
+ Run `eqpt` on a data0 file.
196
+
197
+ All generated files are left in the current working directory, even if an
198
+ error occurs.
199
+
200
+ @param data0 The filepath of an EQ3/6 data0 file
201
+ @param timeout An optional timeout for the command (in seconds)
202
+ @param error_check Whether or not to check the output of the command for errors
203
+
204
+ @return A tuple of the `stdout` and `stderr` output of the command
205
+
206
+ @throws Eq36Error with `RunCode.EQPT_ERROR` if `stdout` includes an error message and `error_check == True`
207
+ @throws Eq36Error with the process' exit code if the command exits with a non-zero exit code (e.g. segfaults)
208
+ @throws Eq36Error with `RunCode.TIMEOUT` if the command times out
209
+ @throws RuntimeError if the `bin` directory does not exist
210
+ @throws RuntimeError if the `eqpt` executable is not found
211
+ @throws OSError if the executable cannot be executed
212
+ """
213
+ return _run(
214
+ get_execpath("eqpt"),
215
+ str(data0),
216
+ timeout=timeout,
217
+ fname=data0,
218
+ code=RunCode.EQPT_ERROR,
219
+ error_check=error_check,
220
+ )
221
+
222
+
223
+ def eq3nr(data1: str | Path, threei: str | Path, timeout: float | None = None) -> tuple[bytes, bytes]:
224
+ """
225
+ Run `eq3nr` on a data1 and a 3i file.
226
+
227
+ All generated files are left in the current working directory, even if an
228
+ error occurs.
229
+
230
+ @param data1 The filepath of an EQ3/6 data1 file
231
+ @param threei The filepath of an EQ3NR input (3i) file
232
+ @param timeout An optional timeout for the command (in seconds)
233
+
234
+ @return A tuple of the `stdout` and `stderr` output of the command
235
+
236
+ @throws Eq36Error with `RunCode.EQ3_ERROR` if `stdout` includes an error message
237
+ @throws Eq36Error with the process' exit code if the command exits with a non-zero exit code (e.g. segfaults)
238
+ @throws Eq36Error with `RunCode.TIMEOUT` if the command times out
239
+ @throws RuntimeError if the `bin` directory does not exist
240
+ @throws RuntimeError if the `eq3nr` executable is not found
241
+ @throws OSError if the executable cannot be executed
242
+ """
243
+ return _run(get_execpath("eq3nr"), str(data1), str(threei), timeout=timeout, fname=threei, code=RunCode.EQ3_ERROR)
244
+
245
+
246
+ def eq6(data1: str | Path, sixi: str | Path, timeout: float | None = None) -> tuple[bytes, bytes]:
247
+ """
248
+ Run `eq6` on a data1 and a 6i file.
249
+
250
+ All generated files are left in the current working directory, even if an
251
+ error occurs.
252
+
253
+ @param data1 The filepath of an EQ3/6 data1 file
254
+ @param sixi The filepath of an EQ6 input (6i) file
255
+ @param timeout An optional timeout for the command (in seconds)
256
+
257
+ @return A tuple of the `stdout` and `stderr` output of the command
258
+
259
+ @throws Eq36Error with `RunCode.EQ6_ERROR` if `stdout` includes an error message
260
+ @throws Eq36Error with the process' exit code if the command exits with a non-zero exit code (e.g. segfaults)
261
+ @throws Eq36Error with `RunCode.TIMEOUT` if the command times out
262
+ @throws RuntimeError if the `bin` directory does not exist
263
+ @throws RuntimeError if the `eq6` executable is not found
264
+ @throws OSError if the executable cannot be executed
265
+ """
266
+ return _run(get_execpath("eq6"), str(data1), str(sixi), timeout=timeout, fname=sixi, code=RunCode.EQ6_ERROR)
eq36/bin/eq3nr.exe ADDED
Binary file
eq36/bin/eq6.exe ADDED
Binary file
eq36/bin/eqpt.exe ADDED
Binary file
eq36/cli.py ADDED
@@ -0,0 +1,110 @@
1
+ """
2
+ Provide executable shims for the compiled EQ3/6 binaries.
3
+
4
+ Providing compiled binaries in wheels is somewhat tricky, especially if you want
5
+ to support a wide variety of machines (as we do). The
6
+ [auditwheel](https://github.com/pypa/auditwheel) tool works wonders and our
7
+ initial, naive approach of simply including the binaries as scripts worked
8
+ great. It worked by placing the delocated binaries and shared libraries in the
9
+ platform directory, installing them next to the main package, and introducing
10
+ shims as scripts. However, we ran into issues on MacOS because
11
+ [delocate](https://github.com/matthew-brett/delocate) does not automatically
12
+ generate the shims.
13
+
14
+ The simple solution is to include the binaries directly inside our main package
15
+ source and then provide our own shims.
16
+ """
17
+
18
+ import os
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ from eq36.paths import get_execpath, remove_exe
23
+
24
+
25
+ def _run(cmd: str) -> None:
26
+ """
27
+ Replace the running process with `cmd`, passing `sys.argv`.
28
+
29
+ The `cmd` is expected to be an EQ3/6 executable that the `get_execpath`
30
+ function can resolve, e.g. one installed as part of this package or in the
31
+ directory given by `EQ36_BIN`. Arguments from `sys.argv` are passed on to
32
+ the executable.
33
+
34
+ If the executable resolves to the running script, e.g. because `EQ36_BIN`
35
+ is the directory containing the shims, an error is raised rather than
36
+ endlessly re-running the shim.
37
+
38
+ @private
39
+
40
+ @param cmd The name of the command to be run, e.g. `"eq6"`
41
+
42
+ @throws RuntimeError if the `bin` directory does not exist
43
+ @throws RuntimeError if `cmd` is not found in the `bin` directory
44
+ @throws RuntimeError if `cmd` resolves to the running shim script
45
+ @throws OSError if the executable cannot be executed
46
+
47
+ @warning This function calls `os.execv` which replaces the current running
48
+ process, so it does not return on success. As such, you probably don't
49
+ want to call it from a script unless you're not planning on doing anything
50
+ else.
51
+ """
52
+ this_script = Path(sys.argv[0]).resolve()
53
+ target = get_execpath(cmd)
54
+ if remove_exe(target) == remove_exe(this_script):
55
+ msg = (
56
+ f"cannot run the target command {str(target)!r} because it points "
57
+ "to a shim script; this is likely because EQ36_BIN was set to the "
58
+ "directory containing the shims"
59
+ )
60
+ raise RuntimeError(msg)
61
+
62
+ os.execv(target, sys.argv)
63
+
64
+
65
+ def eqpt() -> None:
66
+ """
67
+ Replace the running process with `eqpt`, passing `sys.argv`.
68
+
69
+ This is the entry point for the `eqpt` script installed with this package.
70
+
71
+ @throws RuntimeError if the `bin` directory does not exist
72
+ @throws RuntimeError if `eqpt` is not found in the `bin` directory
73
+ @throws RuntimeError if `eqpt` resolves to the running shim script
74
+ @throws OSError if the executable cannot be executed
75
+
76
+ @warning This function does not return on success; see `_run`.
77
+ """
78
+ _run("eqpt")
79
+
80
+
81
+ def eq3nr() -> None:
82
+ """
83
+ Replace the running process with `eq3nr`, passing `sys.argv`.
84
+
85
+ This is the entry point for the `eq3nr` script installed with this package.
86
+
87
+ @throws RuntimeError if the `bin` directory does not exist
88
+ @throws RuntimeError if `eq3nr` is not found in the `bin` directory
89
+ @throws RuntimeError if `eq3nr` resolves to the running shim script
90
+ @throws OSError if the executable cannot be executed
91
+
92
+ @warning This function does not return on success; see `_run`.
93
+ """
94
+ _run("eq3nr")
95
+
96
+
97
+ def eq6() -> None:
98
+ """
99
+ Replace the running process with `eq6`, passing `sys.argv`.
100
+
101
+ This is the entry point for the `eq6` script installed with this package.
102
+
103
+ @throws RuntimeError if the `bin` directory does not exist
104
+ @throws RuntimeError if `eq6` is not found in the `bin` directory
105
+ @throws RuntimeError if `eq6` resolves to the running shim script
106
+ @throws OSError if the executable cannot be executed
107
+
108
+ @warning This function does not return on success; see `_run`.
109
+ """
110
+ _run("eq6")