Override namespace in Python

后端 未结 3 1422
猫巷女王i
猫巷女王i 2020-12-08 00:01

Say there is a folder, \'/home/user/temp/a40bd22344\'. The name is completely random and changes in every iteration. I need to be able to import this folder in Python using

相关标签:
3条回答
  • 2020-12-08 00:02

    Here's one way to do it, without touching sys.path, using the imp module in Python:

    import imp
    
    f, filename, desc = imp.find_module('a40bd22344', ['/home/user/temp/'])
    project = imp.load_module('a40bd22344', f, filename, desc)
    
    project.some_func()
    

    Here is a link to some good documentation on the imp module:

    • imp — Access the import internals
    0 讨论(0)
  • 2020-12-08 00:08

    Sure, project = __import__('a40bd22344') after sys.path is set properly will just work.

    Suppose you want to do it in a function taking the full path as an argument and setting the global import of project properly (as well as magically making import project work afterwards in other modules). Piece of cake:

    def weirdimport(fullpath):
      global project
    
      import os
      import sys
      sys.path.append(os.path.dirname(fullpath))
      try:
          project = __import__(os.path.basename(fullpath))
          sys.modules['project'] = project
      finally:
          del sys.path[-1]
    

    this also leaves sys.path as it found it.

    0 讨论(0)
  • 2020-12-08 00:13

    You first import it with import:

    >>> __import__('temp/a40bd22344')
    <module 'temp/a40bd22344' from 'temp/a40bd22344/__init__.py'>
    

    Then you make sure that this module gets known to Python as project:

    >>> import sys
    >>> sys.modules['project'] = sys.modules.pop('temp/a40bd22344')
    

    After this, anything importing project in the current Python session will get the original module

    >>> import project
    >>> project
    <module 'temp/a40bd22344' from 'temp/a40bd22344/__init__.py'>
    

    This will work also for sub-modules: if you have a foobar.py in the same location you'll get

    >>> import project.foobar
    >>> project.foobar
    <module 'project.foobar' from 'temp/a40bd22344/foobar.py'>
    

    Addendum. Here's what I'm running:

    >>> print sys.version
    2.5.2 (r252:60911, Jul 31 2008, 17:28:52) 
    [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]
    
    0 讨论(0)
提交回复
热议问题