pb-process-tools 4.0.2__tar.gz → 4.1.0__tar.gz

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.
Files changed (25) hide show
  1. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/PKG-INFO +10 -11
  2. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/README.md +8 -6
  3. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/bin/pbpt_clean_db.py +1 -1
  4. pb_process_tools-4.1.0/bin/pbpt_gen_template.py +26 -0
  5. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/pb_process_tools.egg-info/PKG-INFO +10 -11
  6. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/pb_process_tools.egg-info/SOURCES.txt +1 -0
  7. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/pb_process_tools.egg-info/entry_points.txt +1 -0
  8. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/pbprocesstools/__init__.py +3 -3
  9. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/pbprocesstools/pbpt_db_clean.py +7 -4
  10. {pb_process_tools-4.0.2/bin → pb_process_tools-4.1.0/pbprocesstools}/pbpt_gen_template.py +123 -48
  11. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/pbprocesstools/pbpt_process.py +1 -1
  12. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/pbprocesstools/pbpt_q_process.py +174 -2
  13. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/pbprocesstools/pbpt_utils.py +1 -1
  14. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/pyproject.toml +2 -4
  15. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/test/test_pbpt_db_clean.py +28 -0
  16. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/test/test_pbpt_q_process.py +210 -4
  17. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/test/test_pbpt_utils.py +1 -1
  18. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/LICENSE.txt +0 -0
  19. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/MANIFEST.in +0 -0
  20. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/pb_process_tools.egg-info/dependency_links.txt +0 -0
  21. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/pb_process_tools.egg-info/requires.txt +0 -0
  22. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/pb_process_tools.egg-info/top_level.txt +0 -0
  23. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/setup.cfg +0 -0
  24. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/share/loggingconfig.json +0 -0
  25. {pb_process_tools-4.0.2 → pb_process_tools-4.1.0}/test/test_pbpt_process.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pb_process_tools
3
- Version: 4.0.2
3
+ Version: 4.1.0
4
4
  Summary: Tools for batch processing data, including on HPC cluster with slurm.
5
5
  Author-email: Pete Bunting <petebunting@mac.com>
6
6
  License:
@@ -210,13 +210,10 @@ Project-URL: Homepage, https://github.com/remotesensinginfo/pb_process_tools
210
210
  Classifier: Intended Audience :: Developers
211
211
  Classifier: Operating System :: OS Independent
212
212
  Classifier: Programming Language :: Python :: 3
213
- Classifier: Programming Language :: Python :: 3.9
214
- Classifier: Programming Language :: Python :: 3.10
215
- Classifier: Programming Language :: Python :: 3.11
216
213
  Classifier: Programming Language :: Python :: 3.12
217
214
  Classifier: Programming Language :: Python :: 3.13
218
215
  Classifier: Programming Language :: Python :: 3.14
219
- Requires-Python: >=3.9
216
+ Requires-Python: >=3.12
220
217
  Description-Content-Type: text/markdown
221
218
  License-File: LICENSE.txt
222
219
  Requires-Dist: sqlalchemy>=2.0
@@ -238,7 +235,7 @@ Dynamic: license-file
238
235
  [![Tests](https://github.com/remotesensinginfo/pb_process_tools/actions/workflows/main.yml/badge.svg)](https://github.com/remotesensinginfo/pb_process_tools/actions/workflows/main.yml)
239
236
  [![Documentation Status](https://readthedocs.org/projects/pb-process-tools/badge/?version=latest)](https://pb-process-tools.readthedocs.io/en/latest/?badge=latest)
240
237
 
241
- Tools for batch processing workflows as a set of jobs backed by a PostgreSQL job queue. Workflows can execute either on an HPC cluster using Slurm (including job arrays) or on a local workstation using GNU Parallel.
238
+ Tools for batch processing workflows as a set of jobs backed by a PostgreSQL job queue. Workflows can execute either on an HPC cluster using Slurm (including job arrays), on a local Linux/macOS workstation using GNU Parallel, or on Windows using PowerShell (5.1+ and 7+).
242
239
 
243
240
  ## Documentation
244
241
 
@@ -248,7 +245,7 @@ Full documentation, installation guides, CLI references, and examples (including
248
245
 
249
246
  ## Installation
250
247
 
251
- Install `pb_process_tools` (v4.0.1) from the source directory (where `pyproject.toml` is located):
248
+ Install `pb_process_tools` (v4.1.0) from the source directory (where `pyproject.toml` is located):
252
249
 
253
250
  ```bash
254
251
  pip install .
@@ -264,20 +261,22 @@ pip install ".[dev]"
264
261
  ## Quick Start
265
262
 
266
263
  1. Provide your PostgreSQL SQLAlchemy connection string (for example in a file `db_conn.txt` containing `postgresql+psycopg2://user:password@host:5432/dbname`, or via the `PBPT_DB_CONN_STR` environment variable).
267
- 2. Generate a template workflow with a unique `--table` name for the task:
264
+ 2. Generate a template workflow with a unique `--table` name for the task (defaults to `.ps1` PowerShell scripts on Windows and `.sh` Bash/GNU Parallel scripts on Linux/macOS, or pass `--shell powershell` / `--shell bash`):
268
265
 
269
266
  ```bash
270
- pbpt_gen_template.py --output /path/to/out/dir --dbfile db_conn.txt --table my_task_jobs
267
+ pbpt_gen_template --output /path/to/out/dir --dbfile db_conn.txt --table my_task_jobs
271
268
  ```
272
269
 
273
270
  3. Implement `ProcessCmd.do_processing()` in `perform_analysis.py` and job discovery in `GenCmds.gen_command_info()` in `gen_cmds.py`.
274
271
  4. Populate the queue, run, monitor, verify outputs, and clean up:
275
272
 
276
273
  ```bash
277
- ./run_gen_cmds.sh # Populate queue & generate execution scripts
274
+ ./run_gen_cmds.sh # Populate queue & generate execution scripts (Linux/macOS)
278
275
  ./run_exe_analysis.sh # Run jobs (GNU Parallel or sbatch)
279
276
  ./run_status.sh --watch # Monitor live progress, throughput, and ETA
280
277
  ./run_checks.sh -w 8 # Parallel output verification
281
278
  ./run_errors.sh # Inspect errored/incomplete jobs
282
- pbpt_clean_db.py -d db_conn.txt --drop --completed -y # Tidy leftover queue tables
279
+ pbpt_clean_db -d db_conn.txt --drop --completed -y # Tidy leftover queue tables
283
280
  ```
281
+
282
+ On Windows PowerShell, use the generated `.ps1` wrappers (`.\run_gen_cmds.ps1`, `.\run_exe_analysis.ps1`, `.\run_status.ps1`, `.\run_checks.ps1`, `.\run_errors.ps1`, `.\run_reset_errs.ps1`).
@@ -3,7 +3,7 @@
3
3
  [![Tests](https://github.com/remotesensinginfo/pb_process_tools/actions/workflows/main.yml/badge.svg)](https://github.com/remotesensinginfo/pb_process_tools/actions/workflows/main.yml)
4
4
  [![Documentation Status](https://readthedocs.org/projects/pb-process-tools/badge/?version=latest)](https://pb-process-tools.readthedocs.io/en/latest/?badge=latest)
5
5
 
6
- Tools for batch processing workflows as a set of jobs backed by a PostgreSQL job queue. Workflows can execute either on an HPC cluster using Slurm (including job arrays) or on a local workstation using GNU Parallel.
6
+ Tools for batch processing workflows as a set of jobs backed by a PostgreSQL job queue. Workflows can execute either on an HPC cluster using Slurm (including job arrays), on a local Linux/macOS workstation using GNU Parallel, or on Windows using PowerShell (5.1+ and 7+).
7
7
 
8
8
  ## Documentation
9
9
 
@@ -13,7 +13,7 @@ Full documentation, installation guides, CLI references, and examples (including
13
13
 
14
14
  ## Installation
15
15
 
16
- Install `pb_process_tools` (v4.0.1) from the source directory (where `pyproject.toml` is located):
16
+ Install `pb_process_tools` (v4.1.0) from the source directory (where `pyproject.toml` is located):
17
17
 
18
18
  ```bash
19
19
  pip install .
@@ -29,20 +29,22 @@ pip install ".[dev]"
29
29
  ## Quick Start
30
30
 
31
31
  1. Provide your PostgreSQL SQLAlchemy connection string (for example in a file `db_conn.txt` containing `postgresql+psycopg2://user:password@host:5432/dbname`, or via the `PBPT_DB_CONN_STR` environment variable).
32
- 2. Generate a template workflow with a unique `--table` name for the task:
32
+ 2. Generate a template workflow with a unique `--table` name for the task (defaults to `.ps1` PowerShell scripts on Windows and `.sh` Bash/GNU Parallel scripts on Linux/macOS, or pass `--shell powershell` / `--shell bash`):
33
33
 
34
34
  ```bash
35
- pbpt_gen_template.py --output /path/to/out/dir --dbfile db_conn.txt --table my_task_jobs
35
+ pbpt_gen_template --output /path/to/out/dir --dbfile db_conn.txt --table my_task_jobs
36
36
  ```
37
37
 
38
38
  3. Implement `ProcessCmd.do_processing()` in `perform_analysis.py` and job discovery in `GenCmds.gen_command_info()` in `gen_cmds.py`.
39
39
  4. Populate the queue, run, monitor, verify outputs, and clean up:
40
40
 
41
41
  ```bash
42
- ./run_gen_cmds.sh # Populate queue & generate execution scripts
42
+ ./run_gen_cmds.sh # Populate queue & generate execution scripts (Linux/macOS)
43
43
  ./run_exe_analysis.sh # Run jobs (GNU Parallel or sbatch)
44
44
  ./run_status.sh --watch # Monitor live progress, throughput, and ETA
45
45
  ./run_checks.sh -w 8 # Parallel output verification
46
46
  ./run_errors.sh # Inspect errored/incomplete jobs
47
- pbpt_clean_db.py -d db_conn.txt --drop --completed -y # Tidy leftover queue tables
47
+ pbpt_clean_db -d db_conn.txt --drop --completed -y # Tidy leftover queue tables
48
48
  ```
49
+
50
+ On Windows PowerShell, use the generated `.ps1` wrappers (`.\run_gen_cmds.ps1`, `.\run_exe_analysis.ps1`, `.\run_status.ps1`, `.\run_checks.ps1`, `.\run_errors.ps1`, `.\run_reset_errs.ps1`).
@@ -11,7 +11,7 @@
11
11
  # Author: Pete Bunting
12
12
  # Email: pfb@aber.ac.uk
13
13
  # Date: 20/11/2026
14
- # Version: 4.0.1
14
+ # Version: 4.1.0
15
15
  #
16
16
  ############################################################################
17
17
 
@@ -0,0 +1,26 @@
1
+ #! /usr/bin/env python
2
+
3
+ ############################################################################
4
+ # pbpt_gen_template.py
5
+ #
6
+ # Copyright 2023 ARCSI.
7
+ #
8
+ # Purpose: A script to generate a template for running pb_process_tools
9
+ #
10
+ # Author: Pete Bunting
11
+ # Email: pfb@aber.ac.uk
12
+ # Date: 6/1/2023
13
+ # Version: 4.1.0
14
+ #
15
+ ############################################################################
16
+
17
+ from pbprocesstools.pbpt_gen_template import (
18
+ build_arg_parser,
19
+ gen_pb_process_tools_template,
20
+ main,
21
+ )
22
+
23
+ __all__ = ["build_arg_parser", "gen_pb_process_tools_template", "main"]
24
+
25
+ if __name__ == "__main__":
26
+ raise SystemExit(main())
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pb_process_tools
3
- Version: 4.0.2
3
+ Version: 4.1.0
4
4
  Summary: Tools for batch processing data, including on HPC cluster with slurm.
5
5
  Author-email: Pete Bunting <petebunting@mac.com>
6
6
  License:
@@ -210,13 +210,10 @@ Project-URL: Homepage, https://github.com/remotesensinginfo/pb_process_tools
210
210
  Classifier: Intended Audience :: Developers
211
211
  Classifier: Operating System :: OS Independent
212
212
  Classifier: Programming Language :: Python :: 3
213
- Classifier: Programming Language :: Python :: 3.9
214
- Classifier: Programming Language :: Python :: 3.10
215
- Classifier: Programming Language :: Python :: 3.11
216
213
  Classifier: Programming Language :: Python :: 3.12
217
214
  Classifier: Programming Language :: Python :: 3.13
218
215
  Classifier: Programming Language :: Python :: 3.14
219
- Requires-Python: >=3.9
216
+ Requires-Python: >=3.12
220
217
  Description-Content-Type: text/markdown
221
218
  License-File: LICENSE.txt
222
219
  Requires-Dist: sqlalchemy>=2.0
@@ -238,7 +235,7 @@ Dynamic: license-file
238
235
  [![Tests](https://github.com/remotesensinginfo/pb_process_tools/actions/workflows/main.yml/badge.svg)](https://github.com/remotesensinginfo/pb_process_tools/actions/workflows/main.yml)
239
236
  [![Documentation Status](https://readthedocs.org/projects/pb-process-tools/badge/?version=latest)](https://pb-process-tools.readthedocs.io/en/latest/?badge=latest)
240
237
 
241
- Tools for batch processing workflows as a set of jobs backed by a PostgreSQL job queue. Workflows can execute either on an HPC cluster using Slurm (including job arrays) or on a local workstation using GNU Parallel.
238
+ Tools for batch processing workflows as a set of jobs backed by a PostgreSQL job queue. Workflows can execute either on an HPC cluster using Slurm (including job arrays), on a local Linux/macOS workstation using GNU Parallel, or on Windows using PowerShell (5.1+ and 7+).
242
239
 
243
240
  ## Documentation
244
241
 
@@ -248,7 +245,7 @@ Full documentation, installation guides, CLI references, and examples (including
248
245
 
249
246
  ## Installation
250
247
 
251
- Install `pb_process_tools` (v4.0.1) from the source directory (where `pyproject.toml` is located):
248
+ Install `pb_process_tools` (v4.1.0) from the source directory (where `pyproject.toml` is located):
252
249
 
253
250
  ```bash
254
251
  pip install .
@@ -264,20 +261,22 @@ pip install ".[dev]"
264
261
  ## Quick Start
265
262
 
266
263
  1. Provide your PostgreSQL SQLAlchemy connection string (for example in a file `db_conn.txt` containing `postgresql+psycopg2://user:password@host:5432/dbname`, or via the `PBPT_DB_CONN_STR` environment variable).
267
- 2. Generate a template workflow with a unique `--table` name for the task:
264
+ 2. Generate a template workflow with a unique `--table` name for the task (defaults to `.ps1` PowerShell scripts on Windows and `.sh` Bash/GNU Parallel scripts on Linux/macOS, or pass `--shell powershell` / `--shell bash`):
268
265
 
269
266
  ```bash
270
- pbpt_gen_template.py --output /path/to/out/dir --dbfile db_conn.txt --table my_task_jobs
267
+ pbpt_gen_template --output /path/to/out/dir --dbfile db_conn.txt --table my_task_jobs
271
268
  ```
272
269
 
273
270
  3. Implement `ProcessCmd.do_processing()` in `perform_analysis.py` and job discovery in `GenCmds.gen_command_info()` in `gen_cmds.py`.
274
271
  4. Populate the queue, run, monitor, verify outputs, and clean up:
275
272
 
276
273
  ```bash
277
- ./run_gen_cmds.sh # Populate queue & generate execution scripts
274
+ ./run_gen_cmds.sh # Populate queue & generate execution scripts (Linux/macOS)
278
275
  ./run_exe_analysis.sh # Run jobs (GNU Parallel or sbatch)
279
276
  ./run_status.sh --watch # Monitor live progress, throughput, and ETA
280
277
  ./run_checks.sh -w 8 # Parallel output verification
281
278
  ./run_errors.sh # Inspect errored/incomplete jobs
282
- pbpt_clean_db.py -d db_conn.txt --drop --completed -y # Tidy leftover queue tables
279
+ pbpt_clean_db -d db_conn.txt --drop --completed -y # Tidy leftover queue tables
283
280
  ```
281
+
282
+ On Windows PowerShell, use the generated `.ps1` wrappers (`.\run_gen_cmds.ps1`, `.\run_exe_analysis.ps1`, `.\run_status.ps1`, `.\run_checks.ps1`, `.\run_errors.ps1`, `.\run_reset_errs.ps1`).
@@ -12,6 +12,7 @@ pb_process_tools.egg-info/requires.txt
12
12
  pb_process_tools.egg-info/top_level.txt
13
13
  pbprocesstools/__init__.py
14
14
  pbprocesstools/pbpt_db_clean.py
15
+ pbprocesstools/pbpt_gen_template.py
15
16
  pbprocesstools/pbpt_process.py
16
17
  pbprocesstools/pbpt_q_process.py
17
18
  pbprocesstools/pbpt_utils.py
@@ -1,2 +1,3 @@
1
1
  [console_scripts]
2
2
  pbpt_clean_db = pbprocesstools.pbpt_db_clean:main
3
+ pbpt_gen_template = pbprocesstools.pbpt_gen_template:main
@@ -27,7 +27,7 @@ See other source files for details
27
27
  # Author: Pete Bunting
28
28
  # Email: pfb@aber.ac.uk
29
29
  # Date: 12/11/2018
30
- # Version: 4.0.1
30
+ # Version: 4.1.0
31
31
 
32
32
  import json
33
33
  import logging
@@ -36,8 +36,8 @@ import os
36
36
  import sys
37
37
 
38
38
  PB_PROCESS_TOOLS_VERSION_MAJOR = 4
39
- PB_PROCESS_TOOLS_VERSION_MINOR = 0
40
- PB_PROCESS_TOOLS_VERSION_PATCH = 2
39
+ PB_PROCESS_TOOLS_VERSION_MINOR = 1
40
+ PB_PROCESS_TOOLS_VERSION_PATCH = 0
41
41
 
42
42
  PB_PROCESS_TOOLS_VERSION = (
43
43
  f"{PB_PROCESS_TOOLS_VERSION_MAJOR}."
@@ -25,7 +25,7 @@ up leftover PostgreSQL job queue tables created by pb_process_tools.
25
25
  # Author: Pete Bunting
26
26
  # Email: pfb@aber.ac.uk
27
27
  # Date: 20/11/2026
28
- # Version: 4.0.1
28
+ # Version: 4.1.0
29
29
 
30
30
  import argparse
31
31
  import datetime
@@ -33,13 +33,16 @@ import fnmatch
33
33
  import json
34
34
  import logging
35
35
  import os
36
- import sys
37
36
  from typing import Optional
38
37
 
39
38
  import sqlalchemy
40
39
 
41
40
  from pbprocesstools import configure_logging
42
- from pbprocesstools.pbpt_q_process import _DBSessionMixin, _normalize_schema
41
+ from pbprocesstools.pbpt_q_process import (
42
+ _DBSessionMixin,
43
+ _is_interactive_stdin,
44
+ _normalize_schema,
45
+ )
43
46
  from pbprocesstools.pbpt_utils import PBPTUtils
44
47
 
45
48
  logger = logging.getLogger(__name__)
@@ -901,7 +904,7 @@ def _run_drop_mode(
901
904
  f"{skipped_names}"
902
905
  )
903
906
  return 0
904
- if sys.stdin.isatty():
907
+ if _is_interactive_stdin():
905
908
  print(_format_table_report(droppable))
906
909
  resp = (
907
910
  input(f"Drop these {len(droppable)} queue table(s)? [y/N]: ")
@@ -1,5 +1,7 @@
1
1
  #! /usr/bin/env python
2
-
2
+ """
3
+ pb_process_tools - Generate template scripts for batch processing workflows.
4
+ """
3
5
  ############################################################################
4
6
  # pbpt_gen_template.py
5
7
  #
@@ -10,7 +12,7 @@
10
12
  # Author: Pete Bunting
11
13
  # Email: pfb@aber.ac.uk
12
14
  # Date: 6/1/2023
13
- # Version: 4.0.1
15
+ # Version: 4.1.0
14
16
  #
15
17
  ############################################################################
16
18
 
@@ -21,6 +23,7 @@ import shlex
21
23
  import jinja2
22
24
 
23
25
  from pbprocesstools.pbpt_process import PBPTProcessToolsBase
26
+ from pbprocesstools.pbpt_q_process import PBPTGenQProcessToolCmds
24
27
  from pbprocesstools.pbpt_utils import PBPTUtils
25
28
 
26
29
  BLACK_AVAIL = True
@@ -75,6 +78,8 @@ pbpt_gen_cmds_cls_tmplt = """
75
78
  import glob
76
79
  import logging
77
80
  import os
81
+ {% if use_powershell %}import sys
82
+ {% endif %}
78
83
 
79
84
  from pbprocesstools.pbpt_q_process import PBPTGenQProcessToolCmds
80
85
 
@@ -135,6 +140,12 @@ class GenCmds(PBPTGenQProcessToolCmds):
135
140
  # gres=None,
136
141
  # extra_sbatch_args=None,
137
142
  )
143
+ {% elif use_powershell %}
144
+ self.create_powershell_exe(
145
+ run_script="{{ file_prefix }}run_exe_analysis.ps1",
146
+ n_cores=10,
147
+ db_info_file="{{ file_prefix }}pbpt_lcl_db_info.json",
148
+ )
138
149
  {% else %}
139
150
  self.create_shell_exe(
140
151
  run_script="{{ file_prefix }}run_exe_analysis.sh",
@@ -150,6 +161,8 @@ if __name__ == "__main__":
150
161
  py_script = os.path.join(script_dir, "{{ ana_py_file }}")
151
162
  {% if use_singularity %}
152
163
  script_cmd = f"{{ sing_cmd }} python {py_script}"
164
+ {% elif use_powershell %}
165
+ script_cmd = f'"{sys.executable}" "{py_script}"'
153
166
  {% else %}
154
167
  script_cmd = f"python {py_script}"
155
168
  {% endif %}
@@ -170,6 +183,17 @@ if __name__ == "__main__":
170
183
  """
171
184
 
172
185
 
186
+ def _resolve_shell(shell: str) -> str:
187
+ shell_norm = str(shell).strip().lower() if shell is not None else "auto"
188
+ if shell_norm == "auto":
189
+ return "powershell" if os.name == "nt" else "bash"
190
+ if shell_norm in ("bash", "powershell"):
191
+ return shell_norm
192
+ raise ValueError(
193
+ f"Unsupported shell '{shell}'. Expected 'auto', 'bash', or 'powershell'."
194
+ )
195
+
196
+
173
197
  def gen_pb_process_tools_template(
174
198
  output_dir,
175
199
  dbfile=None,
@@ -183,7 +207,9 @@ def gen_pb_process_tools_template(
183
207
  partition="compute",
184
208
  use_array=False,
185
209
  max_concurrent=None,
210
+ shell="auto",
186
211
  ):
212
+ """Generate workflow template Python scripts and shell/PowerShell helpers."""
187
213
  if not os.path.exists(output_dir):
188
214
  raise FileNotFoundError(
189
215
  "Specified output directory does not exist: {}".format(output_dir)
@@ -193,6 +219,8 @@ def gen_pb_process_tools_template(
193
219
  "db_table_name must be specified so each task uses its own database table."
194
220
  )
195
221
  db_table_name = db_table_name.strip()
222
+ resolved_shell = _resolve_shell(shell)
223
+ use_powershell = resolved_shell == "powershell"
196
224
 
197
225
  pbpt_base = PBPTProcessToolsBase()
198
226
  pbpt_utils = PBPTUtils()
@@ -207,46 +235,47 @@ def gen_pb_process_tools_template(
207
235
  sing_cmd = f"singularity exec{sing_paths_bind} {singularity}"
208
236
  use_singularity = True
209
237
 
238
+ script_ext = "ps1" if use_powershell else "sh"
210
239
  gen_py_file_base = "gen_cmds.py"
211
240
  ana_py_file_base = "perform_analysis.py"
212
- run_gen_sh_base = "run_gen_cmds.sh"
213
- run_status_sh_base = "run_status.sh"
214
- run_errors_sh_base = "run_errors.sh"
215
- run_report_sh_base = "run_report.sh"
216
- run_reset_errs_sh_base = "run_reset_errs.sh"
217
- run_check_sh_base = "run_checks.sh"
241
+ run_gen_base = f"run_gen_cmds.{script_ext}"
242
+ run_status_base = f"run_status.{script_ext}"
243
+ run_errors_base = f"run_errors.{script_ext}"
244
+ run_report_base = f"run_report.{script_ext}"
245
+ run_reset_errs_base = f"run_reset_errs.{script_ext}"
246
+ run_check_base = f"run_checks.{script_ext}"
218
247
  file_prefix = ""
219
248
 
220
249
  if (out_file_prefix is not None) and (out_file_prefix != ""):
221
250
  file_prefix = f"{out_file_prefix}_"
222
251
  gen_py_file_base = f"{file_prefix}{gen_py_file_base}"
223
252
  ana_py_file_base = f"{file_prefix}{ana_py_file_base}"
224
- run_gen_sh_base = f"{file_prefix}{run_gen_sh_base}"
225
- run_status_sh_base = f"{file_prefix}{run_status_sh_base}"
226
- run_errors_sh_base = f"{file_prefix}{run_errors_sh_base}"
227
- run_report_sh_base = f"{file_prefix}{run_report_sh_base}"
228
- run_reset_errs_sh_base = f"{file_prefix}{run_reset_errs_sh_base}"
229
- run_check_sh_base = f"{file_prefix}{run_check_sh_base}"
253
+ run_gen_base = f"{file_prefix}{run_gen_base}"
254
+ run_status_base = f"{file_prefix}{run_status_base}"
255
+ run_errors_base = f"{file_prefix}{run_errors_base}"
256
+ run_report_base = f"{file_prefix}{run_report_base}"
257
+ run_reset_errs_base = f"{file_prefix}{run_reset_errs_base}"
258
+ run_check_base = f"{file_prefix}{run_check_base}"
230
259
 
231
260
  gen_py_file = os.path.join(output_dir, gen_py_file_base)
232
261
  ana_py_file = os.path.join(output_dir, ana_py_file_base)
233
262
  ana_py_mod = pbpt_base.get_file_basename(ana_py_file)
234
- run_gen_sh_file = os.path.join(output_dir, run_gen_sh_base)
235
- run_status_sh_file = os.path.join(output_dir, run_status_sh_base)
236
- run_errors_sh_file = os.path.join(output_dir, run_errors_sh_base)
237
- run_report_sh_file = os.path.join(output_dir, run_report_sh_base)
238
- run_reset_errs_sh_file = os.path.join(output_dir, run_reset_errs_sh_base)
239
- run_check_sh_file = os.path.join(output_dir, run_check_sh_base)
263
+ run_gen_file = os.path.join(output_dir, run_gen_base)
264
+ run_status_file = os.path.join(output_dir, run_status_base)
265
+ run_errors_file = os.path.join(output_dir, run_errors_base)
266
+ run_report_file = os.path.join(output_dir, run_report_base)
267
+ run_reset_errs_file = os.path.join(output_dir, run_reset_errs_base)
268
+ run_check_file = os.path.join(output_dir, run_check_base)
240
269
 
241
270
  out_files = [
242
271
  gen_py_file,
243
272
  ana_py_file,
244
- run_gen_sh_file,
245
- run_status_sh_file,
246
- run_errors_sh_file,
247
- run_report_sh_file,
248
- run_reset_errs_sh_file,
249
- run_check_sh_file,
273
+ run_gen_file,
274
+ run_status_file,
275
+ run_errors_file,
276
+ run_report_file,
277
+ run_reset_errs_file,
278
+ run_check_file,
250
279
  ]
251
280
 
252
281
  for out_file in out_files:
@@ -255,7 +284,7 @@ def gen_pb_process_tools_template(
255
284
  f"File already exists, select --overwrite if you "
256
285
  f"wish to overwrite: {out_file}"
257
286
  )
258
- elif os.path.exists(out_file) and overwrite:
287
+ if os.path.exists(out_file) and overwrite:
259
288
  os.remove(out_file)
260
289
 
261
290
  py_cmd = f"{sing_cmd} python" if use_singularity else "python"
@@ -269,6 +298,7 @@ def gen_pb_process_tools_template(
269
298
  "ana_py_mod": ana_py_mod,
270
299
  "sing_cmd": sing_cmd,
271
300
  "use_slurm": bool(use_slurm),
301
+ "use_powershell": use_powershell,
272
302
  "use_singularity": use_singularity,
273
303
  "slurm_module_load": slurm_module_load,
274
304
  "file_prefix": file_prefix,
@@ -298,28 +328,52 @@ def gen_pb_process_tools_template(
298
328
  pbpt_utils.writeData2File(pbpt_gen_cmds_cls_code, gen_py_file)
299
329
  pbpt_utils.writeData2File(pbpt_process_cmd_code, ana_py_file)
300
330
 
301
- quoted_gen_py = shlex.quote(gen_py_file)
302
- sh_scripts = [
303
- (f'#!/bin/bash\n{py_cmd} {quoted_gen_py} --gen "$@"', run_gen_sh_file),
304
- (f'#!/bin/bash\n{py_cmd} {quoted_gen_py} --status "$@"', run_status_sh_file),
305
- (f'#!/bin/bash\n{py_cmd} {quoted_gen_py} --errors "$@"', run_errors_sh_file),
306
- (
307
- f'#!/bin/bash\n{py_cmd} {quoted_gen_py} --report "$@" | more',
308
- run_report_sh_file,
309
- ),
310
- (
311
- f'#!/bin/bash\n{py_cmd} {quoted_gen_py} --rmouts --error "$@"',
312
- run_reset_errs_sh_file,
313
- ),
314
- (f'#!/bin/bash\n{py_cmd} {quoted_gen_py} --check "$@"', run_check_sh_file),
315
- ]
316
- for script_content, script_path in sh_scripts:
317
- pbpt_utils.writeData2File(script_content, script_path)
318
- os.chmod(script_path, 0o755)
319
-
331
+ if use_powershell:
332
+ cmd_tokens = PBPTGenQProcessToolCmds._split_command_line(py_cmd)
333
+ ps_prefix = "& " + " ".join(
334
+ PBPTGenQProcessToolCmds._ps_quote(tok) for tok in cmd_tokens
335
+ )
336
+ ps_gen_py = PBPTGenQProcessToolCmds._ps_quote(gen_py_file)
337
+ wrapper_scripts = [
338
+ (f"{ps_prefix} {ps_gen_py} --gen @args\n", run_gen_file),
339
+ (f"{ps_prefix} {ps_gen_py} --watch @args\n", run_status_file),
340
+ (f"{ps_prefix} {ps_gen_py} --errors @args\n", run_errors_file),
341
+ (f"{ps_prefix} {ps_gen_py} --report @args\n", run_report_file),
342
+ (f"{ps_prefix} {ps_gen_py} --rmouts --error @args\n", run_reset_errs_file),
343
+ (f"{ps_prefix} {ps_gen_py} --check @args\n", run_check_file),
344
+ ]
345
+ for script_content, script_path in wrapper_scripts:
346
+ with open(script_path, "w", encoding="utf-8-sig") as ps_fp:
347
+ ps_fp.write(script_content)
348
+ else:
349
+ quoted_gen_py = shlex.quote(gen_py_file)
350
+ sh_scripts = [
351
+ (f'#!/bin/bash\n{py_cmd} {quoted_gen_py} --gen "$@"', run_gen_file),
352
+ (
353
+ f'#!/bin/bash\nwatch -n 5 {py_cmd} {quoted_gen_py} --status "$@"',
354
+ run_status_file,
355
+ ),
356
+ (f'#!/bin/bash\n{py_cmd} {quoted_gen_py} --errors "$@"', run_errors_file),
357
+ (
358
+ f'#!/bin/bash\n{py_cmd} {quoted_gen_py} --report "$@" | more',
359
+ run_report_file,
360
+ ),
361
+ (
362
+ f'#!/bin/bash\n{py_cmd} {quoted_gen_py} --rmouts --error "$@"',
363
+ run_reset_errs_file,
364
+ ),
365
+ (f'#!/bin/bash\n{py_cmd} {quoted_gen_py} --check "$@"', run_check_file),
366
+ ]
367
+ for script_content, script_path in sh_scripts:
368
+ pbpt_utils.writeData2File(script_content, script_path)
369
+ try:
370
+ os.chmod(script_path, 0o755)
371
+ except OSError:
372
+ pass
320
373
 
321
- if __name__ == "__main__":
322
374
 
375
+ def build_arg_parser() -> argparse.ArgumentParser:
376
+ """Build the CLI argument parser for pbpt_gen_template."""
323
377
  parser = argparse.ArgumentParser(
324
378
  prog="pbpt_gen_template.py",
325
379
  description="Create template files using pb_process_tools",
@@ -361,6 +415,17 @@ if __name__ == "__main__":
361
415
  default=False,
362
416
  help="Setup template to use slurm",
363
417
  )
418
+ parser.add_argument(
419
+ "--shell",
420
+ type=str,
421
+ choices=["auto", "bash", "powershell"],
422
+ default="auto",
423
+ help=(
424
+ "Shell type for local execution and helper scripts: "
425
+ "'auto' (default: 'powershell' on Windows, 'bash' on POSIX), "
426
+ "'bash', or 'powershell'."
427
+ ),
428
+ )
364
429
  parser.add_argument(
365
430
  "--partition",
366
431
  type=str,
@@ -395,8 +460,13 @@ if __name__ == "__main__":
395
460
  default=False,
396
461
  help="Overwrite files if they already exists",
397
462
  )
463
+ return parser
398
464
 
399
- args = parser.parse_args()
465
+
466
+ def main(argv=None) -> int:
467
+ """CLI entrypoint for pbpt_gen_template."""
468
+ parser = build_arg_parser()
469
+ args = parser.parse_args(argv)
400
470
 
401
471
  gen_pb_process_tools_template(
402
472
  args.output,
@@ -411,5 +481,10 @@ if __name__ == "__main__":
411
481
  partition=args.partition,
412
482
  use_array=args.array,
413
483
  max_concurrent=args.max_concurrent,
484
+ shell=args.shell,
414
485
  )
486
+ return 0
487
+
415
488
 
489
+ if __name__ == "__main__":
490
+ raise SystemExit(main())
@@ -25,7 +25,7 @@ pb_process_tools - Base utilities for batch processing data.
25
25
  # Author: Pete Bunting
26
26
  # Email: pfb@aber.ac.uk
27
27
  # Date: 25/03/2020
28
- # Version: 4.0.1
28
+ # Version: 4.1.0
29
29
 
30
30
  import importlib
31
31
  import os
@@ -25,10 +25,11 @@ pb_process_tools - this file has classes for batch processing data using a queue
25
25
  # Author: Pete Bunting
26
26
  # Email: pfb@aber.ac.uk
27
27
  # Date: 13/05/2020
28
- # Version: 4.0.1
28
+ # Version: 4.1.0
29
29
 
30
30
  import argparse
31
31
  import concurrent.futures
32
+ import ctypes
32
33
  import datetime
33
34
  import hashlib
34
35
  import importlib
@@ -94,6 +95,32 @@ def _normalize_schema(schema: Optional[str]) -> Optional[str]:
94
95
  return cleaned if cleaned else None
95
96
 
96
97
 
98
+ def _is_interactive_stdin() -> bool:
99
+ """Return True when stdin is a real interactive terminal (handles Windows NUL)."""
100
+ if sys.stdin is None:
101
+ return False
102
+ isatty_fn = getattr(sys.stdin, "isatty", None)
103
+ if isatty_fn is None or not isatty_fn():
104
+ return False
105
+ # On Windows, os.isatty() returns True for character devices such as NUL
106
+ # (e.g. subprocess.DEVNULL). Check GetConsoleMode unless isatty was mocked.
107
+ if (
108
+ os.name == "nt"
109
+ and getattr(type(isatty_fn), "__module__", "") != "unittest.mock"
110
+ ):
111
+ windll = getattr(ctypes, "windll", None)
112
+ if windll is None:
113
+ return False
114
+ try:
115
+ msvcrt = importlib.import_module("msvcrt")
116
+ handle = msvcrt.get_osfhandle(sys.stdin.fileno())
117
+ mode = ctypes.c_uint()
118
+ return bool(windll.kernel32.GetConsoleMode(handle, ctypes.byref(mode)))
119
+ except (OSError, ValueError, AttributeError):
120
+ return False
121
+ return True
122
+
123
+
97
124
  _JOB_MODEL_CACHE: dict[tuple[str, Optional[str]], type] = {}
98
125
 
99
126
 
@@ -1683,6 +1710,151 @@ class PBPTGenQProcessToolCmds(_DBSessionMixin, PBPTProcessToolsBase):
1683
1710
  pass
1684
1711
  logger.info("Finished creating shell scripts.")
1685
1712
 
1713
+ @staticmethod
1714
+ def _ps_quote(value: str) -> str:
1715
+ """Quote a value as a PowerShell single-quoted literal."""
1716
+ return "'" + str(value).replace("'", "''") + "'"
1717
+
1718
+ @staticmethod
1719
+ def _split_command_line(cmd: str) -> list[str]:
1720
+ """
1721
+ Split a worker command string into executable and argument tokens while
1722
+ preserving Windows backslashes in paths.
1723
+ """
1724
+ if not isinstance(cmd, str) or not cmd.strip():
1725
+ raise ValueError("Worker command (cmd) must be a non-empty string.")
1726
+ tokens: list[str] = []
1727
+ current: list[str] = []
1728
+ quote_char: Optional[str] = None
1729
+ in_token = False
1730
+ i = 0
1731
+ n = len(cmd)
1732
+ while i < n:
1733
+ ch = cmd[i]
1734
+ if quote_char is not None:
1735
+ if ch == quote_char:
1736
+ quote_char = None
1737
+ elif ch == "\\" and quote_char == '"' and i + 1 < n and cmd[i + 1] == '"':
1738
+ current.append('"')
1739
+ i += 1
1740
+ else:
1741
+ current.append(ch)
1742
+ else:
1743
+ if ch.isspace():
1744
+ if in_token:
1745
+ tokens.append("".join(current))
1746
+ current = []
1747
+ in_token = False
1748
+ elif ch in ('"', "'"):
1749
+ quote_char = ch
1750
+ in_token = True
1751
+ else:
1752
+ current.append(ch)
1753
+ in_token = True
1754
+ i += 1
1755
+ if quote_char is not None:
1756
+ raise ValueError(f"Unclosed quote in command string: {cmd!r}")
1757
+ if in_token:
1758
+ tokens.append("".join(current))
1759
+ return tokens
1760
+
1761
+ def create_powershell_exe(
1762
+ self,
1763
+ run_script="run_exe_analysis.ps1",
1764
+ n_cores=4,
1765
+ db_info_file=None,
1766
+ ):
1767
+ """
1768
+ Generate a pure Windows PowerShell (5.1+) script to launch ``n_cores``
1769
+ concurrent worker processes without GNU Parallel.
1770
+
1771
+ :param run_script: Output PowerShell script path (default: ``run_exe_analysis.ps1``).
1772
+ :param n_cores: Number of concurrent worker processes to launch (must be >= 1).
1773
+ :param db_info_file: Optional path for the queue DB info JSON file.
1774
+ """
1775
+ if n_cores < 1:
1776
+ raise ValueError("n_cores must be >= 1.")
1777
+
1778
+ if self.dry_run:
1779
+ print(
1780
+ f"[DRY RUN] Would create PowerShell script '{run_script}' "
1781
+ f"for {n_cores} worker(s)."
1782
+ )
1783
+ return
1784
+
1785
+ cmd_tokens = self._split_command_line(self.cmd)
1786
+ exe_token = cmd_tokens[0]
1787
+ base_args = cmd_tokens[1:]
1788
+
1789
+ logger.info("Create database info file.")
1790
+ db_info_file = self._write_db_info_file(db_info_file)
1791
+
1792
+ worker_args = base_args + ["--dbinfo", db_info_file]
1793
+ quoted_args = ",\n ".join(self._ps_quote(arg) for arg in worker_args)
1794
+
1795
+ ps_lines = [
1796
+ "# Generated by pb_process_tools (compatible with Windows PowerShell 5.1+ and PowerShell 7+)",
1797
+ f"$exe = {self._ps_quote(exe_token)}",
1798
+ "$workerArgs = @(",
1799
+ f" {quoted_args}",
1800
+ ")",
1801
+ f"$nWorkers = {int(n_cores)}",
1802
+ "$workDir = (Get-Location).Path",
1803
+ "$jobs = @()",
1804
+ "",
1805
+ "for ($i = 0; $i -lt $nWorkers; $i++) {",
1806
+ " $jobs += Start-Job -ScriptBlock {",
1807
+ " param($ExePath, $ArgList, $CurrentDir)",
1808
+ " $ErrorActionPreference = 'Continue'",
1809
+ " Set-Location -LiteralPath $CurrentDir",
1810
+ " & $ExePath @ArgList 2>&1 | ForEach-Object {",
1811
+ " if ($_ -is [System.Management.Automation.ErrorRecord]) {",
1812
+ " $_.ToString()",
1813
+ " } else {",
1814
+ " $_",
1815
+ " }",
1816
+ " }",
1817
+ " if ($LASTEXITCODE -ne 0) {",
1818
+ ' throw "Worker exited with code $LASTEXITCODE"',
1819
+ " }",
1820
+ " } -ArgumentList @($exe, $workerArgs, $workDir)",
1821
+ "}",
1822
+ "",
1823
+ "$exitCode = 0",
1824
+ "try {",
1825
+ " while ($jobs | Where-Object { $_.State -eq 'Running' }) {",
1826
+ " $jobs | Receive-Job",
1827
+ " Start-Sleep -Milliseconds 500",
1828
+ " }",
1829
+ " $jobs | Receive-Job",
1830
+ " $failed = @($jobs | Where-Object { $_.State -ne 'Completed' })",
1831
+ " if ($failed.Count -gt 0) {",
1832
+ " foreach ($job in $failed) {",
1833
+ " if ($job.ChildJobs.Count -gt 0 -and $job.ChildJobs[0].JobStateInfo.Reason) {",
1834
+ " Write-Error $job.ChildJobs[0].JobStateInfo.Reason.Message -ErrorAction Continue",
1835
+ " }",
1836
+ " }",
1837
+ " $exitCode = 1",
1838
+ " }",
1839
+ "}",
1840
+ "finally {",
1841
+ " $jobs | Stop-Job -ErrorAction SilentlyContinue",
1842
+ " $jobs | Remove-Job -Force -ErrorAction SilentlyContinue",
1843
+ "}",
1844
+ "",
1845
+ "if ($exitCode -ne 0) {",
1846
+ " exit $exitCode",
1847
+ "}",
1848
+ "",
1849
+ ]
1850
+
1851
+ run_script_parent = os.path.dirname(os.path.abspath(run_script))
1852
+ if run_script_parent:
1853
+ os.makedirs(run_script_parent, exist_ok=True)
1854
+ with open(run_script, "w", encoding="utf-8-sig") as ps_fp:
1855
+ ps_fp.write("\n".join(ps_lines))
1856
+ logger.info("Finished creating PowerShell script.")
1857
+
1686
1858
  def create_slurm_sub_sh(
1687
1859
  self,
1688
1860
  jobname,
@@ -2066,7 +2238,7 @@ class PBPTGenQProcessToolCmds(_DBSessionMixin, PBPTProcessToolsBase):
2066
2238
  print(f"Reset {n_reset} job(s) in database.")
2067
2239
  elif args.drop:
2068
2240
  if not args.yes:
2069
- if sys.stdin.isatty():
2241
+ if _is_interactive_stdin():
2070
2242
  resp = input(
2071
2243
  f"Drop queue table '{self.db_table_name}'? [y/N]: "
2072
2244
  ).strip().lower()
@@ -29,7 +29,7 @@ existing ``pbprocesstools.pbpt_utils`` class interfaces.
29
29
  # Author: Pete Bunting
30
30
  # Email: pfb@aber.ac.uk
31
31
  # Date: 12/11/2018
32
- # Version: 4.0.1
32
+ # Version: 4.1.0
33
33
 
34
34
  import logging
35
35
  import os
@@ -11,14 +11,11 @@ license = {file = "LICENSE.txt"}
11
11
  authors = [
12
12
  {name = "Pete Bunting", email = "petebunting@mac.com"},
13
13
  ]
14
- requires-python = ">=3.9"
14
+ requires-python = ">=3.12"
15
15
  classifiers = [
16
16
  "Intended Audience :: Developers",
17
17
  "Operating System :: OS Independent",
18
18
  "Programming Language :: Python :: 3",
19
- "Programming Language :: Python :: 3.9",
20
- "Programming Language :: Python :: 3.10",
21
- "Programming Language :: Python :: 3.11",
22
19
  "Programming Language :: Python :: 3.12",
23
20
  "Programming Language :: Python :: 3.13",
24
21
  "Programming Language :: Python :: 3.14",
@@ -37,6 +34,7 @@ docs = ["sphinx>=7.0", "sphinx-rtd-theme>=2.0"]
37
34
 
38
35
  [project.scripts]
39
36
  pbpt_clean_db = "pbprocesstools.pbpt_db_clean:main"
37
+ pbpt_gen_template = "pbprocesstools.pbpt_gen_template:main"
40
38
 
41
39
  [project.urls]
42
40
  Homepage = "https://github.com/remotesensinginfo/pb_process_tools"
@@ -568,6 +568,34 @@ class PBPTDatabaseCleanerTest(unittest.TestCase):
568
568
  self.assertIn("Aborted.", tty_buf.getvalue())
569
569
  self.assertIn("Dropped 1 table(s): t_running", tty_buf.getvalue())
570
570
 
571
+ def test_windows_nul_stdin_not_treated_as_interactive(self):
572
+ import types
573
+ from pbprocesstools import pbpt_q_process
574
+
575
+ fake_stdin = unittest.mock.MagicMock()
576
+ fake_stdin.isatty = lambda: True
577
+ fake_stdin.fileno = lambda: 0
578
+ fake_msvcrt = types.SimpleNamespace(get_osfhandle=lambda _fd: 123)
579
+
580
+ fake_kernel32 = unittest.mock.MagicMock()
581
+ fake_kernel32.GetConsoleMode.return_value = 0 # NUL device returns 0
582
+ fake_windll = types.SimpleNamespace(kernel32=fake_kernel32)
583
+
584
+ with unittest.mock.patch.object(pbpt_q_process.os, "name", "nt"):
585
+ with unittest.mock.patch.object(pbpt_q_process.sys, "stdin", fake_stdin):
586
+ with unittest.mock.patch.object(
587
+ pbpt_q_process.ctypes, "windll", fake_windll, create=True
588
+ ):
589
+ with unittest.mock.patch.object(
590
+ pbpt_q_process.importlib,
591
+ "import_module",
592
+ return_value=fake_msvcrt,
593
+ ):
594
+ self.assertFalse(pbpt_q_process._is_interactive_stdin())
595
+
596
+ fake_kernel32.GetConsoleMode.return_value = 1 # Real console
597
+ self.assertTrue(pbpt_q_process._is_interactive_stdin())
598
+
571
599
 
572
600
  if __name__ == "__main__":
573
601
  unittest.main()
@@ -274,6 +274,9 @@ class PBPTQProcessTest(unittest.TestCase):
274
274
  with self.assertRaises(ValueError):
275
275
  gen.reset_jobs()
276
276
 
277
+ @unittest.skipIf(
278
+ os.name == "nt", "Singularity is only supported on Linux/POSIX."
279
+ )
277
280
  def test_gen_template_script_singularity_spacing(self):
278
281
  script_path = os.path.abspath(
279
282
  os.path.join(os.path.dirname(__file__), "..", "bin", "pbpt_gen_template.py")
@@ -293,6 +296,7 @@ class PBPTQProcessTest(unittest.TestCase):
293
296
  use_slurm=True,
294
297
  singularity="/path/to/container.sif",
295
298
  singularity_paths=["/data:/data"],
299
+ shell="bash",
296
300
  )
297
301
  run_gen = pathlib.Path(os.path.join(tmpdir, "run_gen_cmds.sh")).read_text()
298
302
  self.assertIn("container.sif python ", run_gen)
@@ -623,7 +627,8 @@ class PBPTQProcessTest(unittest.TestCase):
623
627
  self.assertEqual(len(run_lines), 2)
624
628
  self.assertEqual(run_lines[0], "#!/bin/bash")
625
629
  self.assertIn("job_array.sbatch", run_lines[1])
626
- self.assertTrue(os.access(run_sh, os.X_OK))
630
+ if os.name != "nt":
631
+ self.assertTrue(os.access(run_sh, os.X_OK))
627
632
 
628
633
  cmds_lines = (
629
634
  pathlib.Path(os.path.join(job_dir, "jobcmds.sh"))
@@ -667,6 +672,8 @@ class PBPTQProcessTest(unittest.TestCase):
667
672
  "-p",
668
673
  "t1",
669
674
  "--slurm",
675
+ "--shell",
676
+ "bash",
670
677
  "--partition",
671
678
  "highmem",
672
679
  "--array",
@@ -709,7 +716,10 @@ class PBPTQProcessTest(unittest.TestCase):
709
716
  for sh_name, flag_snippet in expected_sh_flags.items():
710
717
  sh_path = os.path.join(tmpdir, sh_name)
711
718
  self.assertTrue(os.path.exists(sh_path), f"Missing {sh_name}")
712
- self.assertTrue(os.access(sh_path, os.X_OK), f"Not executable: {sh_name}")
719
+ if os.name != "nt":
720
+ self.assertTrue(
721
+ os.access(sh_path, os.X_OK), f"Not executable: {sh_name}"
722
+ )
713
723
  sh_text = pathlib.Path(sh_path).read_text()
714
724
  self.assertIn(flag_snippet, sh_text)
715
725
 
@@ -1233,7 +1243,8 @@ class PBPTQProcessTest(unittest.TestCase):
1233
1243
  s_run_lines = pathlib.Path(s_run).read_text().strip().splitlines()
1234
1244
  self.assertEqual(len(s_run_lines), 3)
1235
1245
  self.assertEqual(s_run_lines[0], "#!/bin/bash")
1236
- self.assertTrue(os.access(s_run, os.X_OK))
1246
+ if os.name != "nt":
1247
+ self.assertTrue(os.access(s_run, os.X_OK))
1237
1248
  sbatch0 = pathlib.Path(os.path.join(s_dir, "job_file_0.sbatch")).read_text()
1238
1249
  self.assertIn("#SBATCH --account=acct1", sbatch0)
1239
1250
  self.assertNotIn("module load", sbatch0)
@@ -1276,7 +1287,8 @@ class PBPTQProcessTest(unittest.TestCase):
1276
1287
  gen.create_shell_exe(sh_run, sh_cmds, 2, db_info_file=db_info_path)
1277
1288
  sh_lines = pathlib.Path(sh_run).read_text().splitlines()
1278
1289
  self.assertEqual(sh_lines[0], "#!/bin/bash")
1279
- self.assertTrue(os.access(sh_run, os.X_OK))
1290
+ if os.name != "nt":
1291
+ self.assertTrue(os.access(sh_run, os.X_OK))
1280
1292
 
1281
1293
  # 3) Empty-string Slurm options are omitted from sbatch script
1282
1294
  s_run = os.path.join(tmpdir, "sub_empty.sh")
@@ -1497,6 +1509,7 @@ class PBPTQProcessTest(unittest.TestCase):
1497
1509
  singularity=sing,
1498
1510
  singularity_paths=["/data:/data"] if sing else None,
1499
1511
  db_table_name=f"tbl_{idx}",
1512
+ shell="bash",
1500
1513
  )
1501
1514
  gen_file = os.path.join(sub, f"v{idx}_gen_cmds.py")
1502
1515
  ana_file = os.path.join(sub, f"v{idx}_perform_analysis.py")
@@ -1531,12 +1544,14 @@ class PBPTQProcessTest(unittest.TestCase):
1531
1544
  out_file_prefix="v0",
1532
1545
  db_table_name="tbl_0",
1533
1546
  overwrite=False,
1547
+ shell="bash",
1534
1548
  )
1535
1549
  mod.gen_pb_process_tools_template(
1536
1550
  output_dir=v0_dir,
1537
1551
  out_file_prefix="v0",
1538
1552
  db_table_name="tbl_0_new",
1539
1553
  overwrite=True,
1554
+ shell="bash",
1540
1555
  )
1541
1556
  self.assertIn(
1542
1557
  'db_table_name="tbl_0_new"',
@@ -1551,6 +1566,197 @@ class PBPTQProcessTest(unittest.TestCase):
1551
1566
  pathlib.Path(os.path.join(v0_dir, "v0_run_errors.sh")).read_text(),
1552
1567
  )
1553
1568
 
1569
+ def test_create_powershell_exe_and_ps_templates(self):
1570
+ import shutil
1571
+ import unittest.mock
1572
+ from pbprocesstools import pbpt_gen_template
1573
+
1574
+ # 1) Command splitting & PowerShell quoting helpers
1575
+ tokens = PBPTGenQProcessToolCmds._split_command_line(
1576
+ r'''"C:\Program Files\Python311\python.exe" "C:\My Work\O'Brien\worker.py"'''
1577
+ )
1578
+ self.assertEqual(
1579
+ tokens,
1580
+ [
1581
+ r"C:\Program Files\Python311\python.exe",
1582
+ r"C:\My Work\O'Brien\worker.py",
1583
+ ],
1584
+ )
1585
+ self.assertEqual(
1586
+ PBPTGenQProcessToolCmds._ps_quote(r"C:\O'Brien\my dir"),
1587
+ r"'C:\O''Brien\my dir'",
1588
+ )
1589
+ with self.assertRaises(ValueError):
1590
+ PBPTGenQProcessToolCmds._split_command_line(" ")
1591
+ with self.assertRaises(ValueError):
1592
+ PBPTGenQProcessToolCmds._split_command_line('"unclosed')
1593
+
1594
+ with tempfile.TemporaryDirectory() as tmpdir:
1595
+ db_file = os.path.join(tmpdir, "ps_queue.db")
1596
+ db_url = f"sqlite:///{db_file}"
1597
+
1598
+ gen = _DummyGen(
1599
+ jobs_params=[{"val": 1}, {"val": 2}],
1600
+ db_conn_str=db_url,
1601
+ db_table_name="ps_jobs_tbl",
1602
+ process_tools_mod=os.path.splitext(os.path.basename(__file__))[0],
1603
+ process_tools_cls="_DummyWorker",
1604
+ )
1605
+ gen.cmd = r'"C:\Program Files\Python\python.exe" "C:\My Work\perform_analysis.py"'
1606
+
1607
+ with self.assertRaises(ValueError):
1608
+ gen.create_powershell_exe(n_cores=0)
1609
+
1610
+ ps_run = os.path.join(tmpdir, "run_exe_analysis.ps1")
1611
+ ps_dbinfo = os.path.join(tmpdir, "ps_dbinfo.json")
1612
+
1613
+ # dry_run produces no files
1614
+ gen.dry_run = True
1615
+ gen.create_powershell_exe(
1616
+ run_script=ps_run, n_cores=3, db_info_file=ps_dbinfo
1617
+ )
1618
+ gen.dry_run = False
1619
+ self.assertFalse(os.path.exists(ps_run))
1620
+ self.assertFalse(os.path.exists(ps_dbinfo))
1621
+
1622
+ # Non-dry run creates UTF-8 BOM .ps1 compatible with PowerShell 5.1+
1623
+ gen.create_powershell_exe(
1624
+ run_script=ps_run, n_cores=3, db_info_file=ps_dbinfo
1625
+ )
1626
+ self.assertTrue(os.path.exists(ps_run))
1627
+ self.assertTrue(os.path.exists(ps_dbinfo))
1628
+ raw_bytes = pathlib.Path(ps_run).read_bytes()
1629
+ self.assertTrue(raw_bytes.startswith(b"\xef\xbb\xbf"))
1630
+
1631
+ ps_text = pathlib.Path(ps_run).read_text(encoding="utf-8-sig")
1632
+ self.assertIn(r"$exe = 'C:\Program Files\Python\python.exe'", ps_text)
1633
+ self.assertIn(r"'C:\My Work\perform_analysis.py'", ps_text)
1634
+ self.assertIn(f"'{os.path.abspath(ps_dbinfo)}'", ps_text)
1635
+ self.assertIn("$nWorkers = 3", ps_text)
1636
+ self.assertIn("Start-Job", ps_text)
1637
+ self.assertIn("$ErrorActionPreference = 'Continue'", ps_text)
1638
+ self.assertIn("Set-Location -LiteralPath $CurrentDir", ps_text)
1639
+ self.assertIn("& $ExePath @ArgList", ps_text)
1640
+
1641
+ # 2) Template generation with --shell powershell via CLI
1642
+ ps_tmpl_dir = os.path.join(tmpdir, "ps_tmpl")
1643
+ os.makedirs(ps_tmpl_dir)
1644
+ repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
1645
+ script_path = os.path.join(repo_root, "bin", "pbpt_gen_template.py")
1646
+ env = dict(os.environ)
1647
+ env["PYTHONPATH"] = repo_root + (
1648
+ os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else ""
1649
+ )
1650
+
1651
+ proc = subprocess.run(
1652
+ [
1653
+ sys.executable,
1654
+ script_path,
1655
+ "-o",
1656
+ ps_tmpl_dir,
1657
+ "-p",
1658
+ "win",
1659
+ "--table",
1660
+ "win_jobs",
1661
+ "--shell",
1662
+ "powershell",
1663
+ ],
1664
+ env=env,
1665
+ capture_output=True,
1666
+ text=True,
1667
+ check=True,
1668
+ )
1669
+ self.assertEqual(proc.returncode, 0)
1670
+
1671
+ gen_cmds_txt = pathlib.Path(
1672
+ os.path.join(ps_tmpl_dir, "win_gen_cmds.py")
1673
+ ).read_text()
1674
+ compile(gen_cmds_txt, os.path.join(ps_tmpl_dir, "win_gen_cmds.py"), "exec")
1675
+ self.assertIn("create_powershell_exe", gen_cmds_txt)
1676
+ self.assertIn('run_script="win_run_exe_analysis.ps1"', gen_cmds_txt)
1677
+ self.assertIn("sys.executable", gen_cmds_txt)
1678
+
1679
+ expected_ps_flags = {
1680
+ "win_run_gen_cmds.ps1": "--gen @args",
1681
+ "win_run_status.ps1": "--watch @args",
1682
+ "win_run_errors.ps1": "--errors @args",
1683
+ "win_run_report.ps1": "--report @args",
1684
+ "win_run_reset_errs.ps1": "--rmouts --error @args",
1685
+ "win_run_checks.ps1": "--check @args",
1686
+ }
1687
+ for ps_name, snippet in expected_ps_flags.items():
1688
+ p = os.path.join(ps_tmpl_dir, ps_name)
1689
+ self.assertTrue(os.path.exists(p), f"Missing {ps_name}")
1690
+ txt = pathlib.Path(p).read_text(encoding="utf-8-sig")
1691
+ self.assertIn(snippet, txt)
1692
+
1693
+ # 3) shell="auto" resolves to powershell when os.name == "nt"
1694
+ nt_auto_dir = os.path.join(tmpdir, "nt_auto")
1695
+ os.makedirs(nt_auto_dir)
1696
+ with unittest.mock.patch.object(pbpt_gen_template.os, "name", "nt"):
1697
+ pbpt_gen_template.gen_pb_process_tools_template(
1698
+ output_dir=nt_auto_dir,
1699
+ db_table_name="nt_auto_tbl",
1700
+ shell="auto",
1701
+ )
1702
+ self.assertTrue(
1703
+ os.path.exists(os.path.join(nt_auto_dir, "run_gen_cmds.ps1"))
1704
+ )
1705
+ self.assertIn(
1706
+ "create_powershell_exe",
1707
+ pathlib.Path(os.path.join(nt_auto_dir, "gen_cmds.py")).read_text(),
1708
+ )
1709
+
1710
+ with self.assertRaises(ValueError):
1711
+ pbpt_gen_template.gen_pb_process_tools_template(
1712
+ output_dir=nt_auto_dir,
1713
+ db_table_name="bad_shell_tbl",
1714
+ shell="zsh",
1715
+ )
1716
+
1717
+ # 4) If PowerShell (pwsh or powershell.exe) is installed, run an end-to-end execution test
1718
+ ps_exe = shutil.which("pwsh") or shutil.which("powershell")
1719
+ if ps_exe is not None:
1720
+ worker_script = os.path.join(tmpdir, "ps worker.py")
1721
+ out_marker_dir = os.path.join(tmpdir, "ps_markers")
1722
+ os.makedirs(out_marker_dir)
1723
+ pathlib.Path(worker_script).write_text(
1724
+ "import json, sys, pathlib\n"
1725
+ "import rsgispy.tools.strings\n"
1726
+ "# Write a unique marker per worker run\n"
1727
+ "assert '--dbinfo' in sys.argv\n"
1728
+ "dbinfo = json.loads(pathlib.Path(sys.argv[sys.argv.index('--dbinfo') + 1]).read_text())\n"
1729
+ "assert dbinfo['db_table_name'] == 'ps_live_tbl'\n"
1730
+ f"marker = pathlib.Path({out_marker_dir!r}) / (rsgispy.tools.strings.uid_generator(8) + '.ok')\n"
1731
+ "marker.write_text('ok')\n"
1732
+ "sys.stderr.write('worker info log line\\n')\n",
1733
+ encoding="utf-8",
1734
+ )
1735
+ live_gen = _DummyGen(
1736
+ jobs_params=[{"val": 1}],
1737
+ db_conn_str=db_url,
1738
+ db_table_name="ps_live_tbl",
1739
+ )
1740
+ live_gen.cmd = f'"{sys.executable}" "{worker_script}"'
1741
+ live_ps = os.path.join(tmpdir, "live_run.ps1")
1742
+ live_dbinfo = os.path.join(tmpdir, "live_dbinfo.json")
1743
+ live_gen.create_powershell_exe(
1744
+ run_script=live_ps, n_cores=2, db_info_file=live_dbinfo
1745
+ )
1746
+ ps_cmd = [ps_exe, "-NoProfile"]
1747
+ if os.name == "nt":
1748
+ ps_cmd.extend(["-ExecutionPolicy", "Bypass"])
1749
+ ps_cmd.extend(["-File", live_ps])
1750
+ ps_proc = subprocess.run(
1751
+ ps_cmd,
1752
+ cwd=tmpdir,
1753
+ capture_output=True,
1754
+ text=True,
1755
+ check=True,
1756
+ )
1757
+ self.assertEqual(ps_proc.returncode, 0)
1758
+ self.assertEqual(len(list(pathlib.Path(out_marker_dir).glob("*.ok"))), 2)
1759
+
1554
1760
 
1555
1761
  if __name__ == "__main__":
1556
1762
  unittest.main()
@@ -20,7 +20,7 @@ class PBPTUtilsTest(unittest.TestCase):
20
20
  def test_package_init_logging_and_configure(self):
21
21
  import pbprocesstools
22
22
 
23
- self.assertEqual(pbprocesstools.__version__, "4.0.1")
23
+ self.assertEqual(pbprocesstools.__version__, "4.1.0")
24
24
  self.assertIsInstance(pbprocesstools.py_sys_version_flt, float)
25
25
 
26
26
  orig_lvl = os.environ.get("PBPT_LOG_LVL")