-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathvalidations.py
More file actions
30 lines (24 loc) · 896 Bytes
/
validations.py
File metadata and controls
30 lines (24 loc) · 896 Bytes
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
import importlib.util
import tempfile
def execute_code(*, path=None, code=None, allowed_exceptions=None):
"""
Ensure that code written in `path` or in `code` str is executable.
"""
assert (path is None) != (
code is None
), "Must pass either path to code or code as a str."
if path:
_run_code(path, allowed_exceptions)
return
with tempfile.NamedTemporaryFile(suffix=".py", mode="w+t") as temp:
temp.write(code)
_run_code(temp.name, allowed_exceptions)
def _run_code(path, allowed_exceptions=None):
"""Execute the code in `path` in its own namespace."""
allowed_exceptions = allowed_exceptions or ()
spec = importlib.util.spec_from_file_location("output_code", path)
module = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(module)
except allowed_exceptions:
pass