Import a Python source file or compiled file given its path.
(path)
| 405 | return 'problem in %s - %s: %s' % (self.filename, exc, self.value) |
| 406 | |
| 407 | def importfile(path): |
| 408 | """Import a Python source file or compiled file given its path.""" |
| 409 | magic = importlib.util.MAGIC_NUMBER |
| 410 | with open(path, 'rb') as file: |
| 411 | is_bytecode = magic == file.read(len(magic)) |
| 412 | filename = os.path.basename(path) |
| 413 | name, ext = os.path.splitext(filename) |
| 414 | if is_bytecode: |
| 415 | loader = importlib._bootstrap_external.SourcelessFileLoader(name, path) |
| 416 | else: |
| 417 | loader = importlib._bootstrap_external.SourceFileLoader(name, path) |
| 418 | # XXX We probably don't need to pass in the loader here. |
| 419 | spec = importlib.util.spec_from_file_location(name, path, loader=loader) |
| 420 | try: |
| 421 | return importlib._bootstrap._load(spec) |
| 422 | except BaseException as err: |
| 423 | raise ErrorDuringImport(path, err) |
| 424 | |
| 425 | def safeimport(path, forceload=0, cache={}): |
| 426 | """Import a module; handle errors; return None if the module isn't found. |