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