10 examples of 'python import all functions from file' in Python

Every line of 'python import all functions from file' 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
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_modules(source_code: str):
24 results = {}
25 imports = parse_imports(source_code)
26 for import_ in imports:
27 module = import_.module if import_.module else import_.name
28 loaded_module = importlib.import_module(module)
29
30 if not import_.name == module:
31 loaded_module = getattr(loaded_module, import_.name)
32
33 if import_.alias:
34 results[import_.alias] = loaded_module
35 else:
36 results[import_.name] = loaded_module
37
38 return results
11def import_module(name):
12 __import__("%s" % (name,), globals(), locals(), [], -1)
13 return sys.modules[name]
266def _import_functs(mod, dct, names=None):
267 """
268 Maps attributes attrs from the given module into the given dict.
269
270 Args
271 ----
272 dct : dict
273 Dictionary that will contain the mapping
274
275 names : iter of str, optional
276 If supplied, only map attrs that match the given names
277 """
278 if names is None:
279 names = dir(mod)
280 for name in names:
281 if isinstance(name, tuple):
282 name, alias = name
283 else:
284 alias = name
285 if not name[0] == '_':
286 dct[name] = getattr(mod, name)
287 dct[alias] = dct[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())
69def import_module(module_name):
70 '''
71 Imports the specified module by name.
72 '''
73
74 parts = module_name.split('.')
75 module = __import__(module_name)
76 for part in parts[1:]:
77 module = getattr(module, part)
78 return module
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)
19def read_functions(filenames):
20 """Reads the given python files and yields the function arguments from them."""
21 for filename in filenames:
22 # Infer a language from the filename. Theoretically one should derive this from
23 # `requires` stanzas but that'd be stupidly hard to do...
24 lang, _, _ = filename.partition('_')
25 with open(filename) as f:
26 tree = ast.parse(f.read(), f.name)
27 for i, node in enumerate(ast.iter_child_nodes(tree)):
28 if isinstance(node, ast.FunctionDef) and not node.name.startswith('_'):
29 # The c_*** family of functions call through to the cc_family.
30 # They don't have formal argument lists because most things are delegated.
31 if not node.name.startswith('c_'):
32 ds = ast.get_docstring(node)
33 comment, _, _ = ds.partition('\nArgs:\n')
34 comment = textwrap.dedent(' ' + comment.strip())
35 if node.name.startswith('cc_'):
36 alias = node.name.replace('cc_', 'c_')
37 yield node.name, [alias], lang, ds, comment, arg_checks(node)
38 yield alias, [node.name], lang, ds, comment, arg_checks(node)
39 else:
40 yield node.name, None, lang, ds, comment, arg_checks(node)
19def _importfrom(modname):
20 # from .edenscmnative import (where . is looked through this module)
21 fakelocals = {}
22 pkg = __import__("edenscmnative", globals(), fakelocals, [modname], level=0)
23 try:
24 fakelocals[modname] = mod = getattr(pkg, modname)
25 except AttributeError:
26 raise ImportError(r"cannot import name %s" % modname)
27 # force import; fakelocals[modname] may be replaced with the real module
28 getattr(mod, r"__doc__", None)
29 return fakelocals[modname]
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