本文整理匯總了Python中imp.load_source方法的典型用法代碼示例。如果您正苦於以下問題:Python imp.load_source方法的具體用法?Python imp.load_source怎麽用?Python imp.load_source使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類imp
的用法示例。
在下文中一共展示了imp.load_source方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: load_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def load_module(module_name, file_path):
"""
Load a module by name and search path
This function should work with python 2.7 and 3.x
Returns None if Module could not be loaded.
"""
if sys.version_info >= (3,5,):
import importlib.util
spec = importlib.util.spec_from_file_location(module_name, file_path)
if not spec:
return
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
else:
import imp
mod = imp.load_source(module_name, file_path)
return mod
示例2: update
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def update(self, source):
"""
Updates an existing datatype in the arches db
"""
import imp
dt_source = imp.load_source("", source)
details = dt_source.details
self.validate_details(details)
instance = models.DDataType.objects.get(datatype=details["datatype"])
instance.iconclass = details["iconclass"]
instance.modulename = os.path.basename(source)
instance.classname = details["classname"]
instance.defaultwidget = details["defaultwidget"]
instance.defaultconfig = details["defaultconfig"]
instance.configcomponent = details["configcomponent"]
instance.configname = details["configname"]
instance.isgeometric = details["isgeometric"]
instance.issearchable = details["issearchable"]
instance.save()
示例3: get_model
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def get_model(args):
model_fn = os.path.basename(args.model)
model = imp.load_source(model_fn.split('.')[0], args.model).model
if 'result_dir' in args:
dst = '%s/%s' % (args.result_dir, model_fn)
if not os.path.exists(dst):
shutil.copy(args.model, dst)
dst = '%s/%s' % (args.result_dir, os.path.basename(__file__))
if not os.path.exists(dst):
shutil.copy(__file__, dst)
# load model
if args.resume_model is not None:
serializers.load_hdf5(args.resume_model, model)
# prepare model
if args.gpu >= 0:
model.to_gpu()
return model
示例4: main
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def main():
dn_merge = imp.load_source('dn_merge', '../detection/merge_results.py')
file_paths = []
for split_id in range(settings.TEST_SPLIT_NUM):
result_file_path = darknet_tools.append_before_ext(settings.TEST_RESULTS_OUT, '.{}'.format(split_id))
file_paths.append(result_file_path)
print('loading ssd outputs')
unmerged = read(file_paths)
print('doing nms sort')
nms_sorted = dn_merge.do_nms_sort(unmerged, .5)
print('writing results')
dn_merge.write(nms_sorted, os.path.join(settings.PRODUCTS_ROOT, 'proposals.jsonl' if proposal_output else 'detections.jsonl'))
示例5: load_functions
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def load_functions(filepath=None):
if not filepath:
return None
if not os.path.isfile(filepath):
raise IOError("'{}' not found".format(filepath))
mod_name, file_ext = os.path.splitext(os.path.split(filepath)[-1])
if file_ext.lower() == '.py':
py_mod = imp.load_source(mod_name, filepath)
elif file_ext.lower() == '.pyc':
py_mod = imp.load_compiled(mod_name, filepath)
else:
raise ValueError("'{}' does not have the .py or .pyc extension".format(filepath))
return py_mod
示例6: load_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def load_module(self, name, stuff):
file, filename, info = stuff
(suff, mode, type) = info
try:
if type == BUILTIN_MODULE:
return self.hooks.init_builtin(name)
if type == FROZEN_MODULE:
return self.hooks.init_frozen(name)
if type == C_EXTENSION:
m = self.hooks.load_dynamic(name, filename, file)
elif type == PY_SOURCE:
m = self.hooks.load_source(name, filename, file)
elif type == PY_COMPILED:
m = self.hooks.load_compiled(name, filename, file)
elif type == PKG_DIRECTORY:
m = self.hooks.load_package(name, filename, file)
else:
raise ImportError, "Unrecognized module type (%r) for %s" % \
(type, name)
finally:
if file: file.close()
m.__file__ = filename
return m
示例7: test_imp_load_source
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def test_imp_load_source(self):
import os
try:
_x_mod = os.path.join(self.test_dir, "x.py")
self.write_to_file(_x_mod, """
'''some pydoc'''
X = 3.14
""")
with open(_x_mod, "r") as f:
x = imp.load_source("test_imp_load_source_x",
_x_mod,
f)
self.assertEqual(x.__name__, "test_imp_load_source_x")
self.assertEqual(x.X, 3.14)
self.assertEqual(x.__doc__, '''some pydoc''')
finally:
os.unlink(_x_mod)
示例8: import_module_by_path
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def import_module_by_path(path):
name = os.path.splitext(os.path.basename(path))[0]
if sys.version_info[0] == 2:
import imp
return imp.load_source(name, path)
elif sys.version_info[:2] <= (3, 4):
from importlib.machinery import SourceFileLoader
return SourceFileLoader(name, path).load_module()
else:
import importlib.util
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
# ===================================================================
# --- others
# ===================================================================
示例9: _loadFilterFromPath
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def _loadFilterFromPath(self, path, functionName):
"""
_loadFilterFromPath("path/to/a/python/file/withAPen.py", "myFilterPen")
"""
try:
f = open(path, "r")
try:
moduleName = "externalPenBallWizard{0}".format(path.split('/')[-1][:-3])
if moduleName not in sys.modules:
module = imp.load_source(moduleName, path, f)
else:
module = __import__(moduleName, fromlist=[functionName])
result = getattr(module, functionName)
except:
result = None
f.close()
return result
except IOError as e:
print 'Couldn’t load file {0}'.format(e)
示例10: __init__
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def __init__(self, ag_params, policyparams, gpu_id, ngpu):
super(Register_Gtruth_Controller, self).__init__(ag_params, policyparams, gpu_id, ngpu)
self._hp = self._default_hparams()
self._override_defaults(policyparams)
self.reg_tradeoff = np.ones([self._n_cam, self._n_desig]) / self._n_cam / self._n_desig
params = imp.load_source('params', ag_params['current_dir'] + '/gdnconf.py')
self.gdnconf = params.configuration
self.goal_image_warper = setup_gdn(self.gdnconf, gpu_id)
num_reg_images = len(self._hp.register_gtruth)
self.ntask = self._n_desig // num_reg_images
self.visualizer = CEM_Visual_Preparation_Registration()
示例11: __init__
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def __init__(self, ag_params, policyparams, gpu_id, ngpu):
"""
:param ag_params: agent parameter dictionary
:param policyparams: policy parameter dict
:param gpu_id: gpu id
:param ngpu: number of gpus to use
"""
CEMBaseController.__init__(self, ag_params, policyparams)
params = imp.load_source('params', ag_params['current_dir'] + '/conf.py')
netconf = params.configuration
self.predictor = netconf['setup_predictor'](ag_params, netconf, gpu_id, ngpu, self._logger)
self._net_bsize = netconf['batch_size']
self._net_context = netconf['context_frames']
self._hp.start_planning = self._net_context
self._n_cam = netconf['ncam']
self._images, self._verbose_worker = None, None
self._save_actions = None
示例12: load_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def load_module(module_path):
if "/" not in module_path:
import importlib
return importlib.import_module("%s" % module_path, package="armory")
else:
module_name = module_path.split("/")[-1]
if sys.version_info.major == 2:
import imp
return imp.load_source(module_name, module_path + ".py")
else:
import importlib.util
spec = importlib.util.spec_from_file_location(
module_name, module_path + ".py"
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
示例13: main
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def main(options):
feature_conf = imp.load_source("",
os.path.join(config.FEAT_CONF_DIR, options.feature_conf+".py"))
if options.feature_level == 1:
combiner = Combiner(feature_dict=feature_conf.feature_dict,
feature_name=options.feature_name,
feature_suffix=options.feature_suffix,
corr_threshold=options.corr_threshold)
elif options.feature_level > 1:
feature_conf_meta = imp.load_source("",
os.path.join(config.FEAT_CONF_DIR, options.feature_conf_meta+".py"))
combiner = StackingCombiner(feature_list=feature_conf.feature_list,
feature_name=options.feature_name,
feature_suffix=options.feature_suffix,
feature_level=options.feature_level,
meta_feature_dict=feature_conf_meta.feature_dict,
corr_threshold=options.corr_threshold)
combiner.combine()
combiner.save()
示例14: get_settings
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def get_settings(local_config_file_path=None):
swagger_settings = SWAGGER_SETTINGS.copy()
plugin_settings = {}
if local_config_file_path:
custom_config = imp.load_source('config', local_config_file_path)
swagger_settings.update(getattr(custom_config, 'SWAGGER_SETTINGS', dict()))
plugin_settings.update(getattr(custom_config, 'PLUGIN_SETTINGS', dict()))
return swagger_settings, plugin_settings
示例15: get_caffe_pb
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import load_source [as 別名]
def get_caffe_pb():
"""
Get caffe protobuf.
Returns:
The imported caffe protobuf module.
"""
dir = get_dataset_path('caffe')
caffe_pb_file = os.path.join(dir, 'caffe_pb2.py')
if not os.path.isfile(caffe_pb_file):
download(CAFFE_PROTO_URL, dir)
assert os.path.isfile(os.path.join(dir, 'caffe.proto'))
cmd = "protoc --version"
version, ret = subproc_call(cmd, timeout=3)
if ret != 0:
sys.exit(1)
try:
version = version.decode('utf-8')
version = float('.'.join(version.split(' ')[1].split('.')[:2]))
assert version >= 2.7, "Require protoc>=2.7 for Python3"
except Exception:
logger.exception("protoc --version gives: " + str(version))
raise
cmd = 'cd {} && protoc caffe.proto --python_out .'.format(dir)
ret = os.system(cmd)
assert ret == 0, \
"Command `{}` failed!".format(cmd)
assert os.path.isfile(caffe_pb_file), caffe_pb_file
import imp
return imp.load_source('caffepb', caffe_pb_file)