Import a Python source file or compiled file given its path.
(path)
| 470 | return 'problem in %s - %s: %s' % (self.filename, exc, self.value) |
| 471 | |
| 472 | def importfile(path): |
| 473 | """Import a Python source file or compiled file given its path.""" |
| 474 | magic = importlib.util.MAGIC_NUMBER |
| 475 | with open(path, 'rb') as file: |
| 476 | is_bytecode = magic == file.read(len(magic)) |
| 477 | filename = os.path.basename(path) |
| 478 | name, ext = os.path.splitext(filename) |
| 479 | if is_bytecode: |
| 480 | loader = importlib._bootstrap_external.SourcelessFileLoader(name, path) |
| 481 | else: |
| 482 | loader = importlib._bootstrap_external.SourceFileLoader(name, path) |
| 483 | # XXX We probably don't need to pass in the loader here. |
| 484 | spec = importlib.util.spec_from_file_location(name, path, loader=loader) |
| 485 | try: |
| 486 | return importlib._bootstrap._load(spec) |
| 487 | except BaseException as err: |
| 488 | raise ErrorDuringImport(path, err) |
| 489 | |
| 490 | def safeimport(path, forceload=0, cache={}): |
| 491 | """Import a module; handle errors; return None if the module isn't found. |