forked from kyclark/parallelprocs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parallelprocs.py
84 lines (64 loc) · 2.25 KB
/
parallelprocs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""Run commands with (GNU) parallel"""
import os
import sys
import tempfile
import subprocess
from shutil import which
# --------------------------------------------------
def run(commands,
msg='Running job',
parallel=which('parallel'),
num_procs=0,
verbose=False,
halt=0):
"""
Run commands in parallel
Required:
- commands (list(str)): commands
Keyword options:
- parallel (str): path to "parallel", default "which('parallel')"
- num_procs (int): num of concurrent processes, default "0" to use all CPUs
- verbose (bool): print messages to sys.stderr, default "False"
- halt (int): number of failed jobs to trigger halt, default "0" for no halt
Returns:
- True or False depending on success
May raise exceptions, so run with try/except.
"""
if isinstance(commands, str):
commands = [commands]
if not commands:
return False
def tell(s):
if verbose:
print(s, file=sys.stderr)
tell('{} (# jobs = {})'.format(msg, len(commands)))
if parallel and os.path.isfile(parallel):
job_file = tempfile.NamedTemporaryFile(delete=False, mode='wt')
job_file.write('\n'.join(commands))
job_file.close()
cmd = 'parallel {} {} < {}'.format(
'-j {}'.format(num_procs) if num_procs else '',
'--halt soon,fail={}'.format(halt) if halt else '', job_file.name)
try:
out = subprocess.run(cmd,
shell=True,
check=True,
capture_output=True,
text=True)
if out.stdout:
tell(out.stdout)
if out.stderr:
tell(out.stderr)
except subprocess.CalledProcessError as err:
stderr = err.stderr + '\n' if err.stderr else ''
stdout = out.stdout + '\n' if out.stdout else ''
raise Exception('Error: {}{}'.format(stdout, stderr))
finally:
os.remove(job_file.name)
else:
for cmd in commands:
rv, out = subprocess.getstatusoutput(cmd)
if rv != 0:
raise Exception('Failed to run: {}\nError: {}'.format(
cmd, out))
return True