-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathsuperpowers.py
More file actions
87 lines (67 loc) · 1.95 KB
/
superpowers.py
File metadata and controls
87 lines (67 loc) · 1.95 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
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
85
86
87
"""Superpowers which should be sparingly used.
This library contains functions for importing python files and
for running shell commands. Remember, with great power comes great
responsibility.
Authors
* Mirco Ravanelli 2020
* Aku Rouhe 2021
"""
import importlib
import pathlib
import subprocess
def import_from_path(path):
"""Import module from absolute path
Arguments
---------
path : str, pathlib.Path
The path to the module to import
Returns
-------
module
The loaded module
Implementation taken from:
https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
"""
path = pathlib.Path(path)
modulename = path.with_suffix("").name
spec = importlib.util.spec_from_file_location(modulename, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def run_shell(cmd):
"""This function can be used to run a command in the bash shell.
Arguments
---------
cmd : str
Shell command to run.
Returns
-------
bytes
The captured standard output.
bytes
The captured standard error.
int
The returncode.
Raises
------
OSError
If returncode is not 0, i.e., command failed.
Example
-------
>>> out, err, code = run_shell("echo 'hello world'")
>>> _ = out.decode(errors="ignore")
"""
from speechbrain.utils.logger import get_logger
logger = get_logger(__name__)
# Executing the command
p = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True
)
# Capturing standard output and error
(output, err) = p.communicate()
if p.returncode != 0:
raise OSError(err.decode(errors="replace"))
# Adding information in the logger
msg = output.decode(errors="replace") + "\n" + err.decode(errors="replace")
logger.debug(msg)
return output, err, p.returncode