Every line of 'import text file in python' 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.
4 def 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
90 def __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()
60 def _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)
39 def _load_text(text_path): 40 with open(text_path + '.txt', 'r', encoding='utf-8') as fin: 41 text = ' '.join([line.strip() for line in fin.readlines()]) 42 return text
241 def 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
15 def import_readline(): 16 try: 17 import readline 18 except ImportError: 19 sys.path.append('/usr/lib/python2.7/lib-dynload') 20 21 try: 22 import readline 23 except ImportError as e: 24 print('can not import readline:', e) 25 26 import subprocess 27 try: 28 subprocess.check_call('stty icrnl'.split()) 29 except OSError as e: 30 print('can not restore Enter, use Control+J:', e)
252 def _ppimport_importer(self): 253 name = self.__name__ 254 255 try: 256 module = sys.modules[name] 257 except KeyError: 258 raise ImportError,self.__dict__.get('_ppimport_exc_info')[1] 259 if module is not self: 260 exc_info = self.__dict__.get('_ppimport_exc_info') 261 if exc_info is not None: 262 raise PPImportError,\ 263 ''.join(traceback.format_exception(*exc_info)) 264 else: 265 assert module is self,`(module, self)` 266 267 # uninstall loader 268 del sys.modules[name] 269 270 if DEBUG: 271 print 'Executing postponed import for %s' %(name) 272 try: 273 module = __import__(name,None,None,['*']) 274 except Exception,msg: # ImportError: 275 if DEBUG: 276 p_frame = self.__dict__.get('_ppimport_p_frame',None) 277 frame_traceback(p_frame) 278 self.__dict__['_ppimport_exc_info'] = sys.exc_info() 279 raise 280 281 assert isinstance(module,types.ModuleType),`module` 282 283 self.__dict__ = module.__dict__ 284 self.__dict__['_ppimport_module'] = module 285 286 # XXX: Should we check the existence of module.test? Warn? 287 from scipy.base.testing import ScipyTest 288 module.test = ScipyTest(module).test 289 290 return module
20 def load_script(path, module_name): 21 fp, fname = tools.file_open(path, pathinfo=True) 22 fp2 = None 23 24 # pylint: disable=file-builtin,undefined-variable 25 if not isinstance(fp, file): 26 # imp.load_source need a real file object, so we create 27 # one from the file-like object we get from file_open 28 fp2 = os.tmpfile() 29 fp2.write(fp.read()) 30 fp2.seek(0) 31 32 try: 33 return imp.load_source(module_name, fname, fp2 or fp) 34 finally: 35 if fp: 36 fp.close() 37 if fp2: 38 fp2.close()
27 def load_file_as_module(name): 28 path = os.path.join(os.path.dirname(bootstrap_file), "%s.py" % name) 29 if sys.version_info.major >= 3: 30 from importlib import machinery 31 32 mod = machinery.SourceFileLoader(name, path).load_module() 33 else: 34 import imp 35 36 mod = imp.load_source(name, path) 37 return mod
23 def 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