10 examples of 'import python file from different directory' in Python

Every line of 'import python file from different directory' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
69def _import_from(mod, path, mod_dir=None):
70 """
71 Imports a module from a specific path
72
73 :param mod:
74 A unicode string of the module name
75
76 :param path:
77 A unicode string to the directory containing the module
78
79 :param mod_dir:
80 If the sub directory of "path" is different than the "mod" name,
81 pass the sub directory as a unicode string
82
83 :return:
84 None if not loaded, otherwise the module
85 """
86
87 if mod_dir is None:
88 mod_dir = mod
89
90 if not os.path.exists(path):
91 return None
92
93 if not os.path.exists(os.path.join(path, mod_dir)):
94 return None
95
96 try:
97 mod_info = imp.find_module(mod_dir, [path])
98 return imp.load_module(mod, *mod_info)
99 except ImportError:
100 return None
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

8def import_from_file(self, file_path):
9 """
10 Import the specified file, with an unqualified module name.
11 """
12 folder = os.path.dirname(file_path)
13 filename = os.path.basename(file_path)
14 module_name = os.path.splitext(filename)[0]
15 return self.import_module(folder, module_name)
4def import_dir(name, fromlist=()):
5 PACKAGE_EXT = '.sublime-package'
6 dirname = os.path.basename(os.path.dirname(os.path.realpath(__file__)))
7 if dirname.endswith(PACKAGE_EXT):
8 dirname = dirname[:-len(PACKAGE_EXT)]
9 return __import__('{0}.{1}'.format(dirname, name), fromlist=fromlist)
90def __import__(name, globals=None, locals=None, fromlist=None):
91 """An alternative to the import function so that we can import
92 modules defined as strings.
93
94 This code was taken from: http://docs.python.org/lib/examples-imp.html
95 """
96 # Fast path: see if the module has already been imported.
97 try:
98 return sys.modules[name]
99 except KeyError:
100 pass
101
102 # If any of the following calls raises an exception,
103 # there's a problem we can't handle -- let the caller handle it.
104 module_name = name.split('.')[-1]
105 module_path = os.path.join(EXAMPLE_DIR, *name.split('.')[:-1])
106
107 fp, pathname, description = imp.find_module(module_name, [module_path])
108
109 try:
110 return imp.load_module(module_name, fp, pathname, description)
111 finally:
112 # Since we may exit via an exception, close fp explicitly.
113 if fp:
114 fp.close()
90def load_python_file(dir_, filename):
91 """Load a file from the given path as a Python module."""
92
93 module_id = re.sub(r"\W", "_", filename)
94 path = os.path.join(dir_, filename)
95 _, ext = os.path.splitext(filename)
96 if ext == ".py":
97 if os.path.exists(path):
98 module = load_module_py(module_id, path)
99 else:
100 pyc_path = pyc_file_from_path(path)
101 if pyc_path is None:
102 raise ImportError("Can't find Python file %s" % path)
103 else:
104 module = load_module_pyc(module_id, pyc_path)
105 elif ext in (".pyc", ".pyo"):
106 module = load_module_pyc(module_id, path)
107 return module
53def load_python_file(py_file_full_path):
54 if PY2:
55 import imp
56 return imp.load_compiled("module.name", py_file_full_path)
57 elif sys.version_info < (3, 5):
58 raise ParseError("this doesn't work for .pyc files")
59 from importlib.machinery import SourceFileLoader
60 return SourceFileLoader("module.name", py_file_full_path).load_module()
61 else:
62 import importlib.util
63 spec = importlib.util.spec_from_file_location("module.name", py_file_full_path)
64 module = importlib.util.module_from_spec(spec)
65 spec.loader.exec_module(module)
66 return module
4def import_file(path):
5 with open(path) as f:
6 text = f.read() + '\n'
7 try:
8 lexer = Lexer(text=text)
9 tokens = lexer.lex()
10 parser = Parser(tokens=tokens)
11 tree = parser.script()
12 return tree
13 except Exception as ex:
14 raise ex
51def import_modules_from_package(package):
52 """Import modules from package and append into sys.modules
53
54 :param package: Full package name. For example: rally.plugins.openstack
55 """
56 path = [os.path.dirname(rally.__file__), ".."] + package.split(".")
57 path = os.path.join(*path)
58 for root, dirs, files in os.walk(path):
59 for filename in files:
60 if filename.startswith("__") or not filename.endswith(".py"):
61 continue
62 new_package = ".".join(root.split(os.sep)).split("....")[1]
63 module_name = "%s.%s" % (new_package, filename[:-3])
64 if module_name not in sys.modules:
65 sys.modules[module_name] = importlib.import_module(module_name)
241def import_from_path(path, name="esptool"):
242 if not os.path.isfile(path):
243 raise Exception("No such file: %s" % path)
244
245 # Import esptool from the provided location
246 if sys.version_info >= (3,5):
247 import importlib.util
248 spec = importlib.util.spec_from_file_location(name, path)
249 module = importlib.util.module_from_spec(spec)
250 spec.loader.exec_module(module)
251 elif sys.version_info >= (3,3):
252 from importlib.machinery import SourceFileLoader
253 module = SourceFileLoader(name, path).load_module()
254 else:
255 import imp
256 module = imp.load_source(name, path)
257 return module
60def _gimport(name):
61 # we will register imported module into sys.modules with adjusted path.
62 # reason: if we leave dots in place, python emits warning:
63 # RuntimeWarning: Parent module 'lab.nexedi' not found while handling absolute import
64 #
65 # we put every imported module under `golang._gopath.` namespace with '.' changed to '_'
66 modname = 'golang._gopath.' + name.replace('.', '_')
67
68 try:
69 return sys.modules[modname]
70 except KeyError:
71 # not yet imported
72 pass
73
74 # search for module in every GOPATH entry
75 modpath = None
76 gopathv = _gopathv()
77 for g in gopathv:
78 # module: .../name.py
79 modpath = os.path.join(g, 'src', name + '.py')
80 if os.path.exists(modpath):
81 break
82
83 # package: .../name/__init__.py
84 modpath = os.path.join(g, 'src', name, '__init__.py')
85 if os.path.exists(modpath):
86 break
87
88 else:
89 modpath = None
90
91 if modpath is None:
92 raise ImportError('gopath: no module named %s' % name)
93
94
95 # https://stackoverflow.com/a/67692
96 return imp.load_source(modname, modpath)

Related snippets