-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbash_helper.py
More file actions
executable file
·42 lines (37 loc) · 1.65 KB
/
bash_helper.py
File metadata and controls
executable file
·42 lines (37 loc) · 1.65 KB
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
import subprocess
def run_shell(cmd_str, output_to_list=False, delimiter='\n', wait=True):
"""
Function to run shell/bash command in a safe manner.
Parameters
----------
cmd_str: (str)
The shell/bash command to execute
output_to_list: (bool)
Whether to split the output by delimiter and return as a list
delimiter: (str)
Delimiter to split the output by (default is newline)
Return
------
The output of the shell/bash command as a string or list, depending on the value of output_to_list
"""
try:
if wait:
# Run the command using subprocess.run(), capturing the output
result = subprocess.run(cmd_str, check=True, text=True, shell=True, capture_output=True).stdout.strip()
else:
subprocess.Popen(cmd_str, shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
result = None
except subprocess.CalledProcessError as error:
if '#000: /Users/vfonov/src/build/minc-toolkit-v2/HDF5/src/H5F.c line 675 in H5Fclose(): closing file ID failed' in error.stderr:
result = ''
# This is an error produced by the minc toolkit. However, the output files are fine. Hence, the error is ignored.
else:
print(f'The command "{cmd_str}" failed:')
print(error.stderr)
result = ''
# sys.exit()
# Split the output by delimiter and return as a list (if output_to_list is True)
if output_to_list:
result = result.split(delimiter)
# Return the output as a string or list, depending on the value of output_to_list
return result