10 examples of 'python import from folder' in Python

Every line of 'python import from folder' 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
55def _get_module_from_containing_folder(source_path, module_name):
56 # module_name is a module directly inside source_path
57 module = imp.load_source(module_name, source_path)
58 return module
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

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
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()
23def import_from_directory(library, path):
24 """Import a library from a directory outside the path.
25
26 Parameters
27 ----------
28 library: string
29 The name of the library.
30 path: string
31 The path of the folder containing the library.
32
33 """
34 try:
35 return importlib.import_module(library)
36 except ImportError:
37 module_path = os.path.abspath(path)
38 version = sys.version_info
39
40 if version.major == 2:
41 f, filename, desc = imp.find_module(library, [module_path])
42 return imp.load_module(library, f, filename, desc)
43 else:
44 sys.path.append(module_path)
45 return importlib.import_module(library)
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)
25def global_import(rootDir):
26 # 判断传入的路径下是否有“__init__.py”这个文件了,如果没有则创建,否则import会认为没有这个moudle
27 if os.path.exists(rootDir):
28 arr = rootDir.split("/")
29 pathDir = ""
30 for path in arr:
31 pathDir = "%s%s/" % (pathDir, path)
32 if pathDir != "./":
33 if not os.path.exists("%s__init__.py" % pathDir):
34 with open("%s__init__.py" % pathDir, "w") as tmp:
35 del tmp
36 # 遍历文件夹找出app_开头的py文件,导入,注意globals,否则作用域只是在这个函数下
37 for dirName, subdirList, fileList in os.walk(rootDir):
38 for file_name in fileList:
39 if "GN_APP" in file_name and "pyc" not in file_name:
40 impPath = ""
41 if dirName[-1:] != "/":
42 dirName = dirName.replace("\\", "/")
43 impPath = dirName.replace("/", ".")[2:]
44 else:
45 dirName = dirName.replace("\\", "/")
46 impPath = dirName.replace("/", ".")[2:-1]
47 if impPath != "":
48 exe_str = "from %s.%s import * " % (impPath, file_name[:-3])
49 else:
50 exe_str = "from %s import * " % file_name[:-3]
51 print exe_str
52 exec (exe_str, globals())
4def import_path(path):
5 path = os.path.abspath(path)
6 path, file = os.path.split(path)
7 file, ext = os.path.splitext(file)
8 sys.path.append(path)
9 module = __import__(file)
10 sys.path.pop()
11 return module
83def find_modules(folder):
84 """
85 Used to dynamically load custom classes, loads classes under the specified
86 directory
87 """
88 # Use this file's path to get the full path and module names of the module
89 # files to be loaded
90 path = os.path.realpath(__file__)
91 path = os.path.splitext(path)[0]
92 path = os.path.split(path)[0]
93 path = os.path.split(path)[0]
94 path = os.path.join(path, folder)
95
96 for root, dirs, files in os.walk(path):
97 for fname in files:
98 if os.path.splitext(fname)[-1] == '.py':
99 modname = os.path.splitext(fname)[0]
100 try:
101 module=imp.load_source(modname, os.path.join(root,fname))
102 except ImportError:
103 app.logger.debug("Failed to load module %s from %s", modname, os.path.join(root,fname))
104 else:
105 app.logger.debug("Loaded module %s from %s", modname, os.path.join(root,fname))
6def import_by_path(path):
7 """
8 Given a dotted/colon path, like project.module:ClassName.callable,
9 returns the object at the end of the path.
10 """
11 module_path, object_path = path.split(":", 1)
12 target = importlib.import_module(module_path)
13 for bit in object_path.split("."):
14 target = getattr(target, bit)
15 return target

Related snippets