本文整理汇总了Python中importlib.machinery.SourceFileLoader类的典型用法代码示例。如果您正苦于以下问题:Python SourceFileLoader类的具体用法?Python SourceFileLoader怎么用?Python SourceFileLoader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SourceFileLoader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_info_from_module
def get_info_from_module(target):
"""Load the module/package, get its docstring and __version__
"""
log.debug("Loading module %s", target.file)
sl = SourceFileLoader(target.name, str(target.file))
with _module_load_ctx():
m = sl.load_module()
docstring = m.__dict__.get('__doc__', None)
if not docstring:
raise NoDocstringError('Cannot package module without docstring. '
'Please add a docstring to your module.')
module_version = m.__dict__.get('__version__', None)
if not module_version:
raise NoVersionError('Cannot package module without a version string. '
'Please define a `__version__="x.y.z"` in your module.')
if not isinstance(module_version, str):
raise InvalidVersion('__version__ must be a string, not {}.'
.format(type(module_version)))
if not module_version[0].isdigit():
raise InvalidVersion('__version__ must start with a number. It is {!r}.'
.format(module_version))
docstring_lines = docstring.lstrip().splitlines()
return {'summary': docstring_lines[0],
'version': m.__version__}
示例2: load_module
def load_module(module_name, path):
"""Load arbitrary Python source file"""
loader = SourceFileLoader(module_name, path)
spec = spec_from_loader(loader.name, loader)
module = module_from_spec(spec)
loader.exec_module(module)
return module
示例3: load_config
def load_config(self, config_file):
self.test_config_file_read(config_file)
from importlib.machinery import SourceFileLoader
configuration = SourceFileLoader("configuration", config_file).load_module()
configuration._source = config_file
return configuration
示例4: load_race
def load_race(name):
ensure_directories()
base_name = name.lower()
file_name = base_name.replace('-', '_') + ".py"
class_name = ''.join(part.capitalize() for part in base_name.split('-'))
try:
# from this library
Race = getattr(__import__("dndraces"), class_name)
except AttributeError:
# Don't make __pycache__ file in the races directories
sys.dont_write_bytecode = True
try:
# from $HOME
loader = SourceFileLoader(class_name,
os.path.join(HOME_RACES, file_name))
races = loader.load_module()
Race = getattr(races, class_name)
except FileNotFoundError:
try:
# from /etc
loader = SourceFileLoader(class_name,
os.path.join(ETC_RACES, file_name))
races = loader.load_module()
Race = getattr(races, class_name)
except FileNotFoundError:
msg = "Can not find class for " + name + "\n"
msg += 'Looking for class "' + class_name + '" in ' + file_name
raise FileNotFoundError()
return Race
示例5: test_unlock
def test_unlock(self):
for sample in self.samples:
cfg.startaddress = 0x00000000
mod_name = sample[0]
filepath = sample[1]
try:
module = SourceFileLoader(mod_name, filepath).load_module()
except ImportError:
assert(module)
self.opts.interface = 'file'
self.opts.filename = path.join(
path.dirname(__file__), 'samples/') + mod_name + '.bin'
foundtarget = False
for i, target in enumerate(unlock.targets, 1):
if target.signatures[0].os == module.OS:
foundtarget = [target]
self.opts.target_number = i
# print(module.OS)
self.assertTrue(foundtarget)
self.assertIsNotNone(self.opts.target_number)
module.IS_INTRUSIVE = True
sys.stdout = StringIO() # Suppress output
device, memsize = interface.initialize(self.opts, module)
memspace = memory.MemorySpace(device, memsize)
address, page = unlock.run(self.opts, memspace)
sys.stdout = sys.__stdout__ # Restore output
# print(address & 0x00000fff)
# print(module.offset)
#self.assertEqual(address & 0x00000fff, module.offset)
self.assertEqual(page, module.page)
示例6: load
def load(path):
path = pathlib.Path(path) # I hate lines like this so much.
name = path.stem
logging.debug("Loading '%s' definition from %s", name, path)
with path.open() as f:
specs = list(csv.DictReader(f, delimiter="\t"))
base = define_struct(name, specs)
modpath = path.parent.joinpath(name + '.py')
logging.debug("Looking for make_struct hook in %s", modpath)
try:
module = SourceFileLoader(name, str(modpath)).load_module()
except FileNotFoundError:
msg = "Nothing at %s, skipping"
logging.debug(msg, modpath)
return base
if not hasattr(module, "make_struct"):
msg = "%s doesn't contain make_struct, skipping"
logging.debug(msg, modpath)
return base
msg = "Processing hook %s.make_struct for '%s' in %s"
logging.debug(msg, module.__name__, name, path)
newbase = module.make_struct(base)
if not isinstance(newbase, type) or not issubclass(newbase, base):
msg = ("{}.make_struct() in {} failed to return subclass of {}; "
"actually returned: {}")
msg = msg.format(module.__name__, path, base.__name__, newbase)
raise Exception(msg)
return newbase
示例7: load_settings
def load_settings(cfg_path=None):
"""todo: Docstring for load_settings
:param cfg_path: arg description
:type cfg_path: type description
:return:
:rtype:
"""
global settings
cfg_path = cfg_path or _config['cfg_path']
cfg_d = _config.copy()
if os.path.exists(cfg_path):
sfl = SourceFileLoader('upkg_cfg', cfg_path)
cfg_mod = sfl.load_module()
for m in inspect.getmembers(cfg_mod):
if m[0][0] != '_':
cfg_d[m[0]] = m[1]
# end for m in inspect.getme
# Make the paths absolute.
cfg_d["cfg_path"] = _clean_path(cfg_d["cfg_path"])
cfg_d["upkg_destdir"] = _clean_path(cfg_d["upkg_destdir"])
settings = Namespace(**cfg_d)
示例8: send_alert
def send_alert(alert_id, message, log_errors=True):
alert = Alert.query.get(alert_id)
module_config = {}
for option in alert.module_options:
module_config[option.key] = option.value
try:
module_found = False
for module in get_alert_modules():
if module["id"] == alert.module:
module_found = True
if not module_found:
raise AlertExecutionError("Module not found!")
module = SourceFileLoader(
"module.{}".format(alert.module), os.path.join(module_dir, "{}.py".format(alert.module))
).load_module()
module.config = module_config
module.handle_alert(message)
except AlertExecutionError as ex:
if log_errors:
log_message("Alerting - {}".format(alert.module), str(ex))
else:
raise
except Exception as ex:
if log_errors:
log_message(
"Alerting - {}".format(alert.module),
"Could not read " "data from alert module: {}".format(alert.module),
)
else:
raise AlertExecutionError(str(ex))
示例9: loadPlugins
def loadPlugins():
modules = getPythonScriptModules()
print("Found python modules to scan for relink lookup %s" % len(modules))
# print("Modules:")
# modules.sort()
# for module in modules:
# print(' ', module)
ret = {}
for fPath, modName in modules:
# print("Loading", fPath, modName)
try:
loader = SourceFileLoader(modName, fPath)
mod = loader.load_module()
plugClasses = findPluginClass(mod, 'Scrape')
for key, pClass in plugClasses:
if key in ret:
raise ValueError("Two plugins providing an interface with the same name? Name: '%s'" % key)
ret[key] = pClass
except AttributeError:
print("Attribute error!", modName)
traceback.print_exc()
pass
except ImportError:
print("Import error!", modName)
traceback.print_exc()
pass
return ret
示例10: test_gantry_resampling
def test_gantry_resampling(self):
tmp_output_dir = tempfile.mkdtemp()
script_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
'scripts',
'dicom2nifti')
assert os.path.isfile(script_file)
try:
if sys.version_info > (3, 0):
from importlib.machinery import SourceFileLoader
dicom2nifti_module = SourceFileLoader("dicom2nifti_script", script_file).load_module()
else:
import imp
dicom2nifti_module = imp.load_source('dicom2nifti_script', script_file)
dicom2nifti_module.main(['-G', '-r', '-o', '1', '-p', '-1000', test_data.FAILING_ORHTOGONAL, tmp_output_dir])
assert os.path.isfile(os.path.join(tmp_output_dir, "4_dicom2nifti.nii.gz"))
dicom2nifti_module.main(['--allow-gantry-tilting',
'--resample',
'--resample-order', '1',
'--resample-padding', '-1000',
test_data.FAILING_ORHTOGONAL,
tmp_output_dir])
assert os.path.isfile(os.path.join(tmp_output_dir, "4_dicom2nifti.nii.gz"))
finally:
shutil.rmtree(tmp_output_dir)
示例11: JudgeTest
class JudgeTest(ParametrizedTestCase):
'''trybva testovete da ima suffix za da razbera koi test e gramnal '''
solution_module = None
def setUp(self):
self.solution_module = SourceFileLoader("module.name", os.path.join(os.path.dirname(__file__),
'solutions/',
self.param + '.py')).load_module()
@timeout(0.5)
def test_something_0(self):
self.assertEqual(4, self.solution_module.solution(8))
@timeout(1)
def test_something_1(self):
self.assertEqual(2, self.solution_module.solution(4))
@timeout(1)
def test_something_2(self):
self.assertEqual(6, self.solution_module.solution(12))
@timeout(1)
def test_something_3(self):
self.assertEqual(5, self.solution_module.solution(10))
示例12: run_example
def run_example(self, theInput, theOutput):
# Import program (decrapted in 3.4, no other way at the moment)
from importlib.machinery import SourceFileLoader
solution = SourceFileLoader("solution", self.programPath).load_module()
# Feed the input
with PatchStd(theInput) as std:
# Start time counter
startTime = time.time()
# Run the program
solution.main()
# Get end time
endTime = time.time() - startTime
# Get memory (include current tests ~14MB but more or less is that)
mem = memory_usage(max_usage=True)
# Check output
actual_output = std.getStdOut().getvalue()
self.assertEqual(actual_output, theOutput)
# Print time (not do before because output is not yet retrieved)
std.restore()
print("\tTime: %.3f sec" % endTime)
print("\tMemory: %.3f MB" % mem)
# Show errors if any
errors = std.getStdErr().getvalue()
if errors != '':
print("\t" + errors)
示例13: load_module_from_file
def load_module_from_file(name, path):
try:
loaded = SourceFileLoader(name, path)
if isinstance(loaded, types.ModuleType):
return loaded, None
return loaded.load_module(), None
except Exception as error:
return None, error
示例14: return_module
def return_module(self, name='test'):
file_name = path.join(self.out_dir.name, name + '.py')
sys_path.append(self.out_dir.name)
loader = SourceFileLoader(self._testMethodName, file_name)
module = loader.load_module(self._testMethodName)
sys_path.remove(self.out_dir.name)
return module
示例15: load_module_by_path
def load_module_by_path(fpath, module_name=None):
if module_name is None:
module_name = str(uuid())
fpath = os.path.realpath(fpath)
if os.path.isdir(fpath):
fpath = os.path.join(fpath, '__init__.py')
loader = SourceFileLoader(module_name, fpath)
m = loader.load_module()
return m