File: file_loader.py

package info (click to toggle)
crazy-complete 0.3.7-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,528 kB
  • sloc: python: 13,342; sh: 995; makefile: 68
file content (58 lines) | stat: -rw-r--r-- 1,604 bytes parent folder | download
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
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2025-2026 Benjamin Abendroth <braph93@gmx.de>

"""Functions for loading a python file."""

import os
import sys
import importlib
import tempfile
import __main__


def execute_file(file):
    '''Import file using compile + exec.'''
    with open(os.devnull, 'w', encoding='utf-8') as null_fh:
        sys.stdout = null_fh
        sys.stderr = null_fh

        try:
            with open(file, 'r', encoding='utf-8') as fh:
                source = fh.read()
                compiled = compile(source, file, 'exec')
                try:
                    # pylint: disable=exec-used
                    exec(compiled, globals())
                except SystemExit:
                    pass
        finally:
            sys.stdout = sys.__stdout__
            sys.stderr = sys.__stderr__

    return __main__


def import_file(file):
    '''Import file using importlib.'''
    directory, filename = os.path.split(file)
    if filename.lower().endswith('.py'):
        module_name = filename[:-3]
    else:
        temp = tempfile.NamedTemporaryFile(mode='w',
                                           encoding='utf-8',
                                           suffix='.py')

        with open(file, 'r', encoding='utf-8') as fh:
            temp.file.write(fh.read())
            temp.flush()

        directory, file = os.path.split(temp.name)
        module_name = file[:-3]

    if not directory:
        directory = '.'

    if directory not in sys.path:
        sys.path.append(directory)

    return importlib.import_module(module_name)