Is this correct way to import python scripts residing in arbitrary folders?

前端 未结 4 2173
温柔的废话
温柔的废话 2021-01-02 06:09

This snippet is from an earlier answer here on SO. It is about a year old (and the answer was not accepted). I am new to Python and I am finding the system path a real pain.

4条回答
  •  离开以前
    2021-01-02 06:57

    As mentioned, please consider thread safety, if appropriate. I prefer something closer to a solution posted in a similar post. The main differences below: the use of insert to specify priority of the import, correct restoration of sys.path using try...finally, and setting the global namespace.

    # inspired by Alex Martelli's solution to
    # http://stackoverflow.com/questions/1096216/override-namespace-in-python/1096247#1096247
    def import_from_absolute_path(fullpath, global_name=None):
        """Dynamic script import using full path."""
        import os
        import sys
    
        script_dir, filename = os.path.split(fullpath)
        script, ext = os.path.splitext(filename)
    
        sys.path.insert(0, script_dir)
        try:
            module = __import__(script)
            if global_name is None:
                global_name = script
            globals()[global_name] = module
            sys.modules[global_name] = module
        finally:
            del sys.path[0]
    

提交回复
热议问题