本文整理汇总了Python中__import__函数的典型用法代码示例。如果您正苦于以下问题:Python __import__函数的具体用法?Python __import__怎么用?Python __import__使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了__import__函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init_func
def init_func(self, creator_fd, raw_socket_fd, tun_fd, cs, caddr, debug=True):
self.__debug = debug
self.__caddr = caddr
name = "freenet.lib.crypto.%s" % fns_config.configs["tcp_crypto_module"]["name"]
__import__(name)
crypto = sys.modules[name]
args = fns_config.configs["tcp_crypto_module"]["args"]
self.__encrypt = crypto.encrypt(*args)
self.__decrypt = crypto.decrypt(*args)
self.__creator_fd = creator_fd
self.__traffic_send_fd = raw_socket_fd
self.__vlan_ips = []
self.__udp_natp_to_fd = {}
self.__tun_fd = tun_fd
self.set_socket(cs)
self.register(self.fileno)
self.add_evt_read(self.fileno)
self.set_timeout(self.fileno, self.__TIMEOUT_NO_AUTH)
self.print_access_log("connect")
return self.fileno
示例2: get_versions
def get_versions(module_list=None):
if not module_list:
return {}
ext_module_list = set()
for m in module_list:
parts = m.split('.')
ext_module_list.update('.'.join(parts[:idx])
for idx in range(1, len(parts) + 1))
versions = {}
for module_name in ext_module_list:
if module_name not in _VERSION_CACHE:
try:
__import__(module_name)
except ImportError:
continue
try:
app = sys.modules[module_name]
except KeyError:
continue
try:
version = get_version_from_app(module_name, app)
except Exception as e:
logger.exception(e)
version = None
_VERSION_CACHE[module_name] = version
else:
version = _VERSION_CACHE[module_name]
if version is not None:
versions[module_name] = version
return versions
示例3: wrap
def wrap(f):
if modules:
# attach import to function
setattr(f, 'imports', modules)
for alternatives in modules:
# alternatives are comma seperated
alternatives = alternatives.split(',')
# we import the part of the import X.Y.Z -> Z
mod_name = alternatives[0].split('.')[-1]
for mod in alternatives:
mod = mod.strip().split('.')
try:
if len(mod) == 1:
module = __import__(mod[0])
else:
module = getattr(__import__('.'.join(mod[:-1]), \
fromlist=[mod[-1]]), mod[-1])
f.func_globals[mod_name] = module
break # import only one
except ImportError:
pass
else:
if forgive: # no break -> no import
warnings.warn('Failed to import %s' % alternatives)
else:
raise ImportError('Failed to import %s' % alternatives)
return f
示例4: module_exists
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
示例5: load_module
def load_module(module_name):
"""Imports a module given its name and returns a handle to it."""
try:
__import__(module_name)
except ImportError:
raise ImportError('No module named %s' % module_name)
return sys.modules[module_name]
示例6: wrap
def wrap(*args, **kwargs):
__import__('time').sleep(seconds)
try:
result = target(*args, **kwargs)
except:
result = None
return result
示例7: import_module
def import_module(module_name):
"""
Imports a module. A single point of truth for importing modules to
be documented by `pdoc`. In particular, it makes sure that the top
module in `module_name` can be imported by using only the paths in
`pdoc.import_path`.
If a module has already been imported, then its corresponding entry
in `sys.modules` is returned. This means that modules that have
changed on disk cannot be re-imported in the same process and have
its documentation updated.
"""
if import_path != sys.path:
# Such a kludge. Only restrict imports if the `import_path` has
# been changed. We don't want to always restrict imports, since
# providing a path to `imp.find_module` stops it from searching
# in special locations for built ins or frozen modules.
#
# The problem here is that this relies on the `sys.path` not being
# independently changed since the initialization of this module.
# If it is changed, then some packages may fail.
#
# Any other options available?
# Raises an exception if the parent module cannot be imported.
# This hopefully ensures that we only explicitly import modules
# contained in `pdoc.import_path`.
imp.find_module(module_name.split('.')[0], import_path)
if module_name in sys.modules:
return sys.modules[module_name]
else:
__import__(module_name)
return sys.modules[module_name]
示例8: getargs
def getargs(self,moduleName,className,method) :
'''
This will return the list of arguments in a method of python module of class.
It accepts method list as an argument.
'''
print "Message : Argument list is being obtained for each method"
methodArgsDict = {}
if className == None:
moduleList = moduleName.split(".")
for index,name in enumerate(method) :
Module = __import__(moduleList[len(moduleList) -1], globals(), locals(), [moduleList[len(moduleList) -2]], -1)
try :
names = vars(Module)[name]
except KeyError:
print "Message : method '" + name + "'does not exists,Continued with including it. "
return False
argumentList = inspect.getargspec(names) #inspect.getargvalues(name)
methodArgsDict[name] = argumentList[0]
else :
moduleList = moduleName.split(".")
for index,name in enumerate(method) :
Module = __import__(moduleList[len(moduleList) - 1], globals(), locals(), [className], -1)
Class = getattr(Module, className)
try :
names = vars(Class)[name]
except KeyError :
print "Message : method '" + name + "'does not exists,Continued with include it."
return False
argumentList = inspect.getargspec(names) #inspect.getargvalues(name)
methodArgsDict[name] = argumentList[0]
return methodArgsDict
示例9: check_config
def check_config(dbdriver, dbtype, dbhost, dbuser, dbpasswd, testdb):
global DBDRIVER, DBTYPE, DBHOST, DBUSER, DBPASSWD, TESTDB, DBSCHEMA, SQL_FILE
DBDRIVER = dbdriver
DBTYPE = dbtype
DBHOST = dbhost
DBUSER = dbuser
DBPASSWD = dbpasswd
TESTDB = testdb
#Check the database driver is installed:
try:
__import__(DBDRIVER)
except ImportError:
message = "Install %s if you want to use %s with BioSQL " % (DBDRIVER, DBTYPE)
raise MissingExternalDependencyError(message)
try:
if DBDRIVER in ["sqlite3"]:
server = BioSeqDatabase.open_database(driver = DBDRIVER, db = TESTDB)
else:
server = BioSeqDatabase.open_database(driver = DBDRIVER,
user = DBUSER, passwd = DBPASSWD,
host = DBHOST)
server.close()
del server
except Exception, e:
message = "Connection failed, check settings if you plan to use BioSQL: %s" % str(e)
raise MissingExternalDependencyError(message)
示例10: test_package_import__semantics
def test_package_import__semantics(self):
# Generate a couple of broken modules to try importing.
# ...try loading the module when there's a SyntaxError
self.rewrite_file('for')
try: __import__(self.module_name)
except SyntaxError: pass
else: raise RuntimeError, 'Failed to induce SyntaxError'
self.assertNotIn(self.module_name, sys.modules)
self.assertFalse(hasattr(sys.modules[self.package_name], 'foo'))
# ...make up a variable name that isn't bound in __builtins__
var = 'a'
while var in dir(__builtins__):
var += random.choose(string.letters)
# ...make a module that just contains that
self.rewrite_file(var)
try: __import__(self.module_name)
except NameError: pass
else: raise RuntimeError, 'Failed to induce NameError.'
# ...now change the module so that the NameError doesn't
# happen
self.rewrite_file('%s = 1' % var)
module = __import__(self.module_name).foo
self.assertEqual(getattr(module, var), 1)
示例11: getmethods
def getmethods(self,modulePath,Class) :
'''
This will get the list of methods in given module or class.
It accepts the module path and class name. If there is no
class name then it has be mentioned as None.
'''
methodList = []
moduleList = modulePath.split("/")
newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
print "Message : Method list is being obatined , Please wait ..."
try :
if Class :
Module = __import__(moduleList[len(moduleList) - 1], globals(), locals(), [Class], -1)
ClassList = [x.__name__ for x in Module.__dict__.values() if inspect.isclass(x)]
self.ClassList = ClassList
Class = vars(Module)[Class]
methodList = [x.__name__ for x in Class.__dict__.values() if inspect.isfunction(x)]
else :
Module = __import__(moduleList[len(moduleList) - 1], globals(), locals(),[moduleList[len(moduleList) - 2]], -1)
methodList = [x.__name__ for x in Module.__dict__.values() if inspect.isfunction(x)]
ClassList = [x.__name__ for x in Module.__dict__.values() if inspect.isclass(x)]
self.ClassList = ClassList
except :
print "Error : " +str(sys.exc_info()[1])
self.method = methodList
return self.method
示例12: main
def main(listener_fd, alive_r, preload, main_path=None, sys_path=None):
'''Run forkserver.'''
if preload:
if '__main__' in preload and main_path is not None:
process.current_process()._inheriting = True
try:
spawn.import_main_path(main_path)
finally:
del process.current_process()._inheriting
for modname in preload:
try:
__import__(modname)
except ImportError:
pass
util._close_stdin()
# ignoring SIGCHLD means no need to reap zombie processes
# letting SIGINT through avoids KeyboardInterrupt tracebacks
handlers = {
signal.SIGCHLD: signal.SIG_IGN,
signal.SIGINT: signal.SIG_DFL,
}
old_handlers = {sig: signal.signal(sig, val)
for (sig, val) in handlers.items()}
with socket.socket(socket.AF_UNIX, fileno=listener_fd) as listener, \
selectors.DefaultSelector() as selector:
_forkserver._forkserver_address = listener.getsockname()
selector.register(listener, selectors.EVENT_READ)
selector.register(alive_r, selectors.EVENT_READ)
while True:
try:
while True:
rfds = [key.fileobj for (key, events) in selector.select()]
if rfds:
break
if alive_r in rfds:
# EOF because no more client processes left
assert os.read(alive_r, 1) == b''
raise SystemExit
assert listener in rfds
with listener.accept()[0] as s:
code = 1
if os.fork() == 0:
try:
_serve_one(s, listener, alive_r, old_handlers)
except Exception:
sys.excepthook(*sys.exc_info())
sys.stderr.flush()
finally:
os._exit(code)
except OSError as e:
if e.errno != errno.ECONNABORTED:
raise
示例13: import_backends
def import_backends():
"""
Import files in the duplicity/backends directory where
the filename ends in 'backend.py' and ignore the rest.
@rtype: void
@return: void
"""
path = duplicity.backends.__path__[0]
assert path.endswith("duplicity/backends"), duplicity.backends.__path__
files = os.listdir(path)
files.sort()
for fn in files:
if fn.endswith("backend.py"):
fn = fn[:-3]
imp = "duplicity.backends.%s" % (fn,)
try:
__import__(imp)
res = "Succeeded"
except Exception:
res = "Failed: " + str(sys.exc_info()[1])
log.Log(_("Import of %s %s") % (imp, res), log.INFO)
else:
continue
示例14: get_config
def get_config(config_path):
__import__('errbot.config-template') # - is on purpose, it should not be imported normally ;)
template = sys.modules['errbot.config-template']
config_fullpath = config_path
if not path.exists(config_fullpath):
log.error(
'I cannot find the file %s \n'
'(You can change this path with the -c parameter see --help)' % config_path
)
log.info(
'You can use the template %s as a base and copy it to %s. \nYou can then customize it.' % (
path.dirname(template.__file__) + sep + 'config-template.py', config_path + sep)
)
exit(-1)
# noinspection PyBroadException
try:
config = __import__(path.splitext(path.basename(config_fullpath))[0])
diffs = [item for item in set(dir(template)) - set(dir(config)) if not item.startswith('_')]
if diffs:
log.error('You are missing configs defined from the template :')
for diff in diffs:
log.error('Missing config : %s' % diff)
exit(-1)
except Exception as _:
log.exception('I could not import your config from %s, please check the error below...' % config_fullpath)
exit(-1)
log.info('Config check passed...')
return config
示例15: find_controller
def find_controller(self, controller):
"""Locates a controller by attempting to import it then grab
the SomeController instance from the imported module.
Override this to change how the controller object is found once
the URL has been resolved.
"""
# Check to see if we've cached the class instance for this name
if controller in self.controller_classes:
return self.controller_classes[controller]
# Pull the controllers class name, import controller
full_module_name = self.package_name + '.controllers.' \
+ controller.replace('/', '.')
# Hide the traceback here if the import fails (bad syntax and such)
__traceback_hide__ = 'before_and_this'
__import__(full_module_name)
if hasattr(sys.modules[full_module_name], '__controller__'):
mycontroller = getattr(
sys.modules[full_module_name],
sys.modules[full_module_name].__controller__)
else:
module_name = controller.split('/')[-1]
class_name = class_name_from_module_name(module_name) + \
'Controller'
if self.log_debug:
log.debug("Found controller, module: '%s', class: '%s'",
full_module_name, class_name)
mycontroller = getattr(sys.modules[full_module_name], class_name)
self.controller_classes[controller] = mycontroller
return mycontroller