Debian Codegraph @

crazy_complete/file_loader.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]>
3
4 """Functions for loading a python file."""
5
6 import os
7 import sys
8 import importlib
9 import tempfile
10 import __main__
11
12
13 def execute_file(file):
14 '''Import file using compile + exec.'''
15 with open(os.devnull, 'w', encoding='utf-8') as null_fh:
16 sys.stdout = null_fh
17 sys.stderr = null_fh
18
19 try:
20 with open(file, 'r', encoding='utf-8') as fh:
21 source = fh.read()
22 compiled = compile(source, file, 'exec')
23 try:
24 # pylint: disable=exec-used
25 exec(compiled, globals())
26 except SystemExit:
27 pass
28 finally:
29 sys.stdout = sys.__stdout__
30 sys.stderr = sys.__stderr__
31
32 return __main__
33
34
35 def import_file(file):
36 '''Import file using importlib.'''
37 directory, filename = os.path.split(file)
38 if filename.lower().endswith('.py'):
39 module_name = filename[:-3]
40 else:
41 temp = tempfile.NamedTemporaryFile(mode='w',
42 encoding='utf-8',
43 suffix='.py')
44
45 with open(file, 'r', encoding='utf-8') as fh:
46 temp.file.write(fh.read())
47 temp.flush()
48
49 directory, file = os.path.split(temp.name)
50 module_name = file[:-3]
51
52 if not directory:
53 directory = '.'
54
55 if directory not in sys.path:
56 sys.path.append(directory)
57
58 return importlib.import_module(module_name)