当前位置: 首页>>代码示例>>Python>>正文


Python PluginManager.locatePlugins方法代码示例

本文整理汇总了Python中yapsy.PluginManager.PluginManager.locatePlugins方法的典型用法代码示例。如果您正苦于以下问题:Python PluginManager.locatePlugins方法的具体用法?Python PluginManager.locatePlugins怎么用?Python PluginManager.locatePlugins使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在yapsy.PluginManager.PluginManager的用法示例。


在下文中一共展示了PluginManager.locatePlugins方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: testTwoStepsLoad

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
	def testTwoStepsLoad(self):
		"""
		Test loading the plugins in two steps in order to collect more
		deltailed informations.
		"""
		spm = PluginManager(directories_list=[
				os.path.join(
					os.path.dirname(os.path.abspath(__file__)),"plugins")])
		# trigger the first step to look up for plugins
		spm.locatePlugins()
		# make full use of the "feedback" the loadPlugins can give
		# - set-up the callback function that will be called *before*
		# loading each plugin
		callback_infos = []
		def preload_cbk(plugin_info):
			callback_infos.append(plugin_info)
		# - gather infos about the processed plugins (loaded or not)
		loadedPlugins = spm.loadPlugins(callback=preload_cbk)
		self.assertEqual(len(loadedPlugins),1)
		self.assertEqual(len(callback_infos),1)
		self.assertEqual(loadedPlugins[0].error,None)
		self.assertEqual(loadedPlugins[0],callback_infos[0])
		# check that the getCategories works
		self.assertEqual(len(spm.getCategories()),1)
		sole_category = spm.getCategories()[0]
		# check the getPluginsOfCategory
		self.assertEqual(len(spm.getPluginsOfCategory(sole_category)),1)
		plugin_info = spm.getPluginsOfCategory(sole_category)[0]
		# try to remove it and check that is worked
		spm.removePluginFromCategory(plugin_info,sole_category)
		self.assertEqual(len(spm.getPluginsOfCategory(sole_category)),0)
		# now re-add this plugin the to same category
		spm.appendPluginToCategory(plugin_info,sole_category)
		self.assertEqual(len(spm.getPluginsOfCategory(sole_category)),1)
开发者ID:eaglexmw,项目名称:codimension,代码行数:36,代码来源:test_SimplePlugin.py

示例2: load_plugins

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
 def load_plugins(parser, logger=None):
     """Load all plugins"""
     # import yapsy if needed
     try:
         from yapsy.PluginManager import PluginManager
     except ImportError:
         parser.exit(status=3, message='PASTA plugins require yapsy.\n'
             'See README file for more informations.\n'
             'Alternatively, use the option --no-plugins to disable the'
             ' plugins\n')
     from plugins import SingleConnectionAnalyser, \
             InterConnectionsAnalyser
     # create the plugin manager
     plugin_manager = PluginManager(
             categories_filter={
                     'SingleConnectionAnalyser': SingleConnectionAnalyser,
                     'InterConnectionsAnalyser': InterConnectionsAnalyser
                 },
             directories_list = [os.path.join(os.path.dirname(sys.argv[0]),
                     'plugins')],
             plugin_info_ext='plugin')
     plugin_manager.locatePlugins()
     def load_plugin(plugin):
         """A plugin is being loaded"""
         if logger is not None:
             logger.info('...plugin %s v.%s'
                     % (plugin.name, plugin.version))
     plugin_manager.loadPlugins(load_plugin)
     return plugin_manager
开发者ID:carriercomm,项目名称:PASTA,代码行数:31,代码来源:pasta.py

示例3: testTwoStepsLoadWithError

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
    def testTwoStepsLoadWithError(self):
        """
		Test loading the plugins in two steps in order to collect more
		deltailed informations and take care of an erroneous plugin.
		"""
        spm = PluginManager(
            directories_list=[os.path.join(os.path.dirname(os.path.abspath(__file__)), "plugins")],
            plugin_info_ext="yapsy-error-plugin",
        )
        # trigger the first step to look up for plugins
        spm.locatePlugins()
        # make full use of the "feedback" the loadPlugins can give
        # - set-up the callback function that will be called *before*
        # loading each plugin
        callback_infos = []

        def preload_cbk(i_plugin_info):
            callback_infos.append(i_plugin_info)
            # - gather infos about the processed plugins (loaded or not)
            # and for the test, monkey patch the logger

        originalLogLevel = log.getEffectiveLevel()
        log.setLevel(logging.ERROR)
        errorLogCallFlag = [False]

        def errorMock(*args, **kwargs):
            errorLogCallFlag[0] = True

        originalErrorMethod = log.error
        log.error = errorMock
        try:
            loadedPlugins = spm.loadPlugins(callback=preload_cbk)
        finally:
            log.setLevel(originalLogLevel)
            log.error = originalErrorMethod
        self.assertTrue(errorLogCallFlag[0])
        self.assertEqual(len(loadedPlugins), 1)
        self.assertEqual(len(callback_infos), 1)
        self.assertTrue(isinstance(callback_infos[0].error, tuple))
        self.assertEqual(loadedPlugins[0], callback_infos[0])
        self.assertEqual(callback_infos[0].error[0], ImportError)
        # check that the getCategories works
        self.assertEqual(len(spm.getCategories()), 1)
        sole_category = spm.getCategories()[0]
        # check the getPluginsOfCategory
        self.assertEqual(len(spm.getPluginsOfCategory(sole_category)), 0)
开发者ID:nyimbi,项目名称:codimension,代码行数:48,代码来源:test_ErrorInPlugin.py

示例4: testCandidatesManipulation

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
	def testCandidatesManipulation(self):
		"""
		Test querying, removing and adding plugins from/to the lkist
		of plugins to load.
		"""
		spm = PluginManager(directories_list=[
				os.path.join(
					os.path.dirname(os.path.abspath(__file__)),"plugins")])
		# locate the plugins that should be loaded
		spm.locatePlugins()
		# check nb of candidatesx
		self.assertEqual(len(spm.getPluginCandidates()),1)
		# get the description of the plugin candidate
		candidate = spm.getPluginCandidates()[0]
		self.assertTrue(isinstance(candidate,tuple))
		# try removing the candidate
		spm.removePluginCandidate(candidate)
		self.assertEqual(len(spm.getPluginCandidates()),0)
		# try re-adding it
		spm.appendPluginCandidate(candidate)
		self.assertEqual(len(spm.getPluginCandidates()),1)
开发者ID:eaglexmw,项目名称:codimension,代码行数:23,代码来源:test_SimplePlugin.py

示例5: load_plugins

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
def load_plugins():
    """ Load plugin for environment. See lib/base.py
    """
    # Create plugin manager
    manager = PluginManager()
    # Tell it the default place(s) where to find plugins
    manager.setPluginPlaces(["pylons_yapsy_plugin/plugins/"])
    # Define the various categories corresponding to the different
    # kinds of plugins you have defined
    manager.setCategoriesFilter({
        "Menu" : menu.Menu,
        "Inline" : inline.Inline,
        })

    manager.locatePlugins()

    # Deactivate plugin
    # Список деактивированных плагинов из БД
    deactivatedPlugins = [plugin.name for plugin in\
            s.query(DeactivatedPlugins).all()]

    # Список кандидатов на загрузку
    candidates = manager.getPluginCandidates()
    # Список деактивированных плагинов в формате yapsy
    deactivatedList = []

    for candidate in candidates:
        if candidate[2].name in deactivatedPlugins:
            deactivatedList.append(candidate)

    # Исключаем плагины которые указанны в БД
    for plugin in deactivatedList:
        manager.removePluginCandidate(plugin)

    # Load plugins
    manager.loadPlugins()

    return manager, [plugin[2] for plugin in deactivatedList]
开发者ID:uralbash,项目名称:pylons_yapsy_plugin,代码行数:40,代码来源:plugins.py

示例6: WUnpack

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
class WUnpack(QtGui.QDialog):
    
    def __init__(self, parent, plugin):
        super(WUnpack, self).__init__(parent)
        
        self.parent = parent
        self.plugin = plugin
        self.oshow = super(WUnpack, self).show

        root = os.path.dirname(sys.argv[0])

        self.ui = PyQt4.uic.loadUi(os.path.join(root, 'unpack.ui'), baseinstance=self)


        self.ui.setWindowTitle('Decrypt/Encrypt')


        self.manager = PluginManager(categories_filter={ "UnpackPlugin": DecryptPlugin})

        root = os.path.dirname(sys.argv[0])
        self.manager.setPluginPlaces([os.path.join(root, 'plugins', 'unpack')])
        #self.manager.setPluginPlaces(["plugins"])

        # Load plugins
        self.manager.locatePlugins()
        self.manager.loadPlugins()

        self.Plugins = {}
        Formats = []
        for plugin in self.manager.getPluginsOfCategory("UnpackPlugin"):
            # plugin.plugin_object is an instance of the plugin
            po = plugin.plugin_object
            if po.init(self.parent.dataModel, self.parent.viewMode):
                self.Plugins[plugin.name] = po
                #self.ui.horizontalLayout.addWidget(po.getUI())
                print '[+] ' + plugin.name
                self.ui.listWidget.addItem(plugin.name)
                #Formats.append(po)

        self.ui.listWidget.currentItemChanged.connect(self.item_clicked)
        self.ui.listWidget.setCurrentRow(0)

        self.ui.connect(self.ui.proceed, PyQt4.QtCore.SIGNAL("clicked()"), self.handleProceed)

        self.initUI()

    def handleProceed(self):
        item = str(self.ui.listWidget.currentItem().text())
        self.Plugins[item].proceed()
        #self.parent.update()
        self.parent.viewMode.draw(refresh=True)
        self.parent.update()

    def item_clicked(self, current, previous):
        #item = str(self.ui.listWidget.currentItem().text())
        item = str(current.text())
        if previous:
            x = self.ui.horizontalLayout.takeAt(0)
            while x:
                x.widget().setParent(None)
                x = self.ui.horizontalLayout.takeAt(0)
                
            prev = str(previous.text())
            #print prev
            #self.ui.horizontalLayout.removeWidget(self.Plugins[prev].getUI())

        if item:
            #print item
            po = self.Plugins[item]
            self.ui.horizontalLayout.addWidget(po.getUI())
        

    def show(self):

        # TODO: remember position? resize plugin windows when parent resize?
        pwidth = self.parent.parent.size().width()
        pheight = self.parent.parent.size().height()

        width = self.ui.size().width()+15
        height = self.ui.size().height()+15

        self.setGeometry(pwidth - width - 15, pheight - height, width, height)
        self.setFixedSize(width, height)

        self.oshow()

    def initUI(self):      

        self.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)

        shortcut = QtGui.QShortcut(QtGui.QKeySequence("F4"), self, self.close, self.close)
        #QtCore.QObject.connect(self.ui.ok, QtCore.SIGNAL('clicked()'), self.onClicked)

    def onClicked(self):
        
        dataModel = self.parent.dataModel
        self.close()
开发者ID:gh0std4ncer,项目名称:qiew,代码行数:99,代码来源:qiew.py

示例7: binWidget

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
class binWidget(QtGui.QWidget, Observable):
  
    scrolled = QtCore.pyqtSignal(int, name='scroll')
    oldscrolled = QtCore.SIGNAL('scroll')

    def __init__(self, parent, source):
        super(binWidget, self).__init__()
        Observable.__init__(self)
        self.parent = parent
        
        # offset for text window
        #self.data = mapped
        self.dataOffset = 0
        
        self.dataModel = source
        self.cursor = Cursor(0, 0)

        
#        self.multipleViewModes = [BinViewMode(self.size().width(), self.size().height(), self.dataModel, self.cursor, self),
#                                  HexViewMode(self.size().width(), self.size().height(), self.dataModel, self.cursor, self)]

        logging.basicConfig(level=logging.ERROR)
        self.manager = PluginManager(categories_filter={ "FileFormat": FileFormat})

        root = os.path.dirname(sys.argv[0])
        self.manager.setPluginPlaces([os.path.join(root, 'plugins', 'format')])
        #self.manager.setPluginPlaces(["plugins"])

        # Load plugins
        self.manager.locatePlugins()
        self.manager.loadPlugins()

        Formats = []
        for plugin in self.manager.getPluginsOfCategory("FileFormat"):
            # plugin.plugin_object is an instance of the plugin
            po = plugin.plugin_object
            if po.recognize(self.dataModel):
                print '[+] ' + po.name
                Formats.append(po)
                

        # sort plugins by priority
        Formats = sorted(Formats, key=lambda x: x.priority, reverse=True)
        po = Formats[0]
        print 'Choosed plugin: ' + po.name

        #print QtGui.QFontDatabase.addApplicationFont(os.path.join('terminus-ttf-4.39', 'TerminusTTF-4.39.ttf'))
        


        self.multipleViewModes = [BinViewMode(self.size().width(), self.size().height(), self.dataModel, self.cursor, self, plugin=po),
                                  HexViewMode(self.size().width(), self.size().height(), self.dataModel, self.cursor, self, plugin=po),
                                  DisasmViewMode(self.size().width(), self.size().height(), self.dataModel, self.cursor, self, plugin=po)]

        self.viewMode = self.multipleViewModes[0]

        self.textDecorator = TextDecorator(self.viewMode)

        self.viewMode.setTransformationEngine(self.textDecorator)

        self.multipleViewModes[1].setTransformationEngine(self.textDecorator)

        self.Banners = Banners()

        #self.Banners.add(BottomBanner(self.dataModel, self.viewMode))
#        self.Banners.add(TopBanner(self.dataModel, self.viewMode))


        #self.Banners.add(self.banner)
#        self.filebanner = FileAddrBanner(self.dataModel, self.viewMode)
        #self.filebanner = PEBanner(self.dataModel, self.viewMode)
        #self.Banners.add(PEBanner(self.dataModel, self.viewMode))
        #self.Banners.add(FileAddrBanner(self.dataModel, self.viewMode))
        #self.Banners.add(FileAddrBanner(self.dataModel, self.viewMode))        

        # self.offsetWindow_h = self.filebanner.getDesiredGeometry()[0] + 25
        self.offsetWindow_h = 0
        self.offsetWindow_v = 0
        self.searchable = Searchable(self.dataModel, self.viewMode)


        self.initUI()
        
        [po.init(viewMode, parent=self) for viewMode in self.multipleViewModes]

        for banner in po.getBanners():
            self.Banners.add(banner)
        
        po.registerShortcuts(self)
        self.po = po

        #self.scrolled = QtCore.pyqtSignal(int, name='scroll')
        #self.scrolled.connect(self.scroll_from_outside)
        self.searchWindow = SearchWindow(self, None, self.searchable)

        self.addHandler(self.po)
        self.addHandler(self.searchable)
        self.addHandler(self.Banners)

        self.notify(self.viewMode)
#.........这里部分代码省略.........
开发者ID:gh0std4ncer,项目名称:qiew,代码行数:103,代码来源:qiew.py

示例8: ContentModelListener

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
class ContentModelListener(ConnectionListener):
    '''
    classdocs
    '''
    def __init__(self, content_models, host='localhost', port=61613, user='', passcode='', fedora_url=''):
        '''
        Constructor
        '''
        self.conn = Connection([(host, port)], user, passcode)
        self.conn.set_listener('', self)
        self.conn.start()
        logging.info('Connecting to STOMP server %(host)s on port %(port)s.' % {'host': host, 'port': port})
        self.transaction_id = None
        logging.info("Connecting to Fedora server at %(url)s" % {'url': fedora_url})
        self.fc = fcrepo.connection.Connection(fedora_url, username = user, password = passcode)
        self.client = FedoraClient(self.fc)
        self.fedora_url = fedora_url
        self.username = user
        self.password = passcode
        
        # Create plugin manager
        self.manager = PluginManager(categories_filter = {"FedoraMicroService": FedoraMicroService})
        plugin_path = os.path.dirname(__file__)
        self.manager.setPluginPlaces([plugin_path + "/plugins"])
        logging.debug("Plugin path: " + plugin_path + "/plugins")
        
        # Load plugins.
        self.manager.locatePlugins()
        self.manager.loadPlugins()
        self.contentModels = {}
        
        for plugin in self.manager.getPluginsOfCategory("FedoraMicroService"):
            # plugin.plugin_object is an instance of the plubin
            logging.info("Loading plugin: %(name)s for content model %(cmodel)s." % {'name': plugin.plugin_object.name, 'cmodel': plugin.plugin_object.content_model})
            plugin.plugin_object.config = config
            if type(plugin.plugin_object.content_model) == types.StringType:
                content_models = [plugin.plugin_object.content_model]
            else:
                content_models = plugin.plugin_object.content_model
            for content_model in content_models:
                if content_model in self.contentModels:
                    self.contentModels[content_model].append(plugin.plugin_object)
                else:
                    self.contentModels[content_model] = [plugin.plugin_object]
    
    def __print_async(self, frame_type, headers, body):
        """
        Utility function for printing messages.
        """
        #logging.debug("\r  \r", end='')
        logging.debug(frame_type)
        for header_key in headers.keys():
            logging.debug('%s: %s' % (header_key, headers[header_key]))
        logging.debug(body)
    
    def on_connecting(self, host_and_port):
        """
        \see ConnectionListener::on_connecting
        """
        self.conn.connect(wait=True)
        
    def on_disconnected(self):
        """
        \see ConnectionListener::on_disconnected
        """
        logging.error("lost connection reconnect in %d sec..." % reconnect_wait)
        signal.alarm(reconnect_wait)
        
    def on_message(self, headers, body):
        """
        \see ConnectionListener::on_message
        """ 

        try:
            global TOPIC_PREFIX
            self.__print_async('MESSAGE', headers, body)
            pid = headers['pid']
            dsid = headers['dsid']
            
            obj = self.client.getObject(pid)
            content_model = headers['destination'][len(TOPIC_PREFIX):]
            if content_model in self.contentModels:
                logging.info('Running rules for %(pid)s from %(cmodel)s.' % {'pid': obj.pid, 'cmodel': content_model} )
                for plugin in self.contentModels[content_model]: 
                    plugin.runRules(obj, dsid, body)

        except FedoraConnectionException:
            logging.warning('Object %s was not found.' % (pid))

        except:
            logging.error("an exception occurred: " + str(sys.exc_info()[0]))


    def on_error(self, headers, body):
        """
        \see ConnectionListener::on_error
        """
        self.__print_async("ERROR", headers, body)
        
    def on_connected(self, headers, body):
#.........这里部分代码省略.........
开发者ID:jesterhazy,项目名称:fedora_microservices,代码行数:103,代码来源:__main__.py

示例9: ModuleManager

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
class ModuleManager():
    def __init__(self, threads, kill_list, kill_list_lock, job_list, binpath):
        self.threads = threads
        self.kill_list = kill_list
        self.kill_list_lock = kill_list_lock
        self.job_list = job_list # Running jobs
        self.binpath = binpath

        self.root_path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', '..'))
        self.module_bin_path = os.path.join(self.root_path, "module_bin")
        self.plugin_path = os.path.join(self.root_path, "lib", "assembly", "plugins")

        self.pmanager = PluginManager()
        locator = self.pmanager.getPluginLocator()
        locator.setPluginInfoExtension('asm-plugin')
        self.pmanager.setPluginPlaces([ self.plugin_path ])
        self.pmanager.collectPlugins()
        self.pmanager.locatePlugins()
        self.plugins = ['none']
        num_plugins = len(self.pmanager.getAllPlugins())
        if  num_plugins == 0:
            raise Exception("No Plugins Found!")

        plugins = []
        self.executables = {}
        for plugin in self.pmanager.getAllPlugins():
            plugin.threads = threads
            self.plugins.append(plugin.name)
            plugin.plugin_object.setname(plugin.name)
            ## Check for installed binaries
            try:
                version = plugin.details.get('Documentation', 'Version')
                executables = plugin.details.items('Executables')
                full_execs = [(k, self.get_executable_path(v)) for k,v in executables]
                for binary in full_execs:
                    if not os.path.exists(binary[1]):
                        if float(version) < 1:
                            print '[Warning]: {} (v{}) -- Binary does not exist for beta plugin -- {}'.format(plugin.name, version, binary[1])
                        else:
                            raise Exception('[ERROR]: {} (v{})-- Binary does not exist -- {}'.format(plugin.name, version, binary[1]))
                self.executables[plugin.name] = full_execs
            except ConfigParser.NoSectionError: pass
            plugins.append(plugin.name)
        print "Plugins found [{}]: {}".format(num_plugins, sorted(plugins))


    def run_proc(self, module, wlink, job_data, parameters):
        """ Run module adapter for wasp interpreter
        To support the Job_data mechanism, injects wlink
        """
        if not self.has_plugin(module):
            raise Exception("No plugin named {}".format(module))
        plugin = self.pmanager.getPluginByName(module)

        config_settings = plugin.details.items('Settings')
        config_settings = update_settings(config_settings, parameters)

        try:
            settings = {k:v for k,v in self.executables[module]}
            for k,v in config_settings: ## Don't override
                if not k in settings:
                    settings[k] = v
            settings = settings.items()
        except:
            # settings = config_settings
            raise Exception("Plugin Config not updated: {}!".format(module))

        #### Check input/output type compatibility
        if wlink['link']:
            for link in wlink['link']:
                if not link:
                    continue
                if link['module']:
                    try:
                        assert (self.output_type(link['module']) == self.input_type(module) or
                                self.output_type(link['module']) in self.input_type(module))
                    except AssertionError:
                        raise Exception('{} and {} have mismatched input/output types'.format(module, link['module']))
        #### Run
        job_data['wasp_chain'] = wlink
        output = plugin.plugin_object.base_call(settings, job_data, self)
        ot = self.output_type(module)
        wlink.insert_output(output, ot,
                            plugin.name)
        if not wlink.output:
            raise Exception('"{}" module failed to produce {}'.format(module, ot))


    def output_type(self, module):
        return self.pmanager.getPluginByName(module).plugin_object.OUTPUT

    def input_type(self, module):
        return self.pmanager.getPluginByName(module).plugin_object.INPUT

    def get_short_name(self, module):
        try:
            plugin = self.pmanager.getPluginByName(module)
            settings = plugin.details.items('Settings')
            for kv in settings:
                if kv[0] == 'short_name':
#.........这里部分代码省略.........
开发者ID:fw1121,项目名称:assembly,代码行数:103,代码来源:plugins.py

示例10: PluginManager

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
        self.build_pkg_hook_args=""
        self.version=None
        self.define_env_version=None
        self.config_version_db_path="/var/tmp/dbversion.db"
        self.config_version_db=None

plugin_dir = os.path.expanduser("~/.repacked/plugins")

if not os.path.exists(plugin_dir):
    plugin_dir = os.path.join(os.path.dirname(__file__),'../../repacked/plugins')

pkg_plugins = {}

pluginMgr = PluginManager(plugin_info_ext="plugin")
pluginMgr.setPluginPlaces([plugin_dir])
pluginMgr.locatePlugins()
pluginMgr.loadPlugins()

for pluginInfo in pluginMgr.getAllPlugins():
   pluginMgr.activatePluginByName(pluginInfo.name)

def parse_spec(filename):
    """
    Loads the YAML file into a Python object for parsing
    and returns it
    """

    fp = open(filename, 'r')
    spec = yaml.safe_load("\n".join(fp.readlines()))

    return spec
开发者ID:haad,项目名称:repacked,代码行数:33,代码来源:repacked.py

示例11: app

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
class app():
    db = None  # the sqlite database of plugins
    plugins = None  # Configured plugins
    storage = None  # The plugin to use for storage
    PluginFolder = None  # Folder where the plugins are
    MinionFolder = None  # Folder where the minions are
    score = None  # the plugin to use for scoring
    classify = None  # the clasification plugin
    helper = None  # The verum helper functions
    loc = None  # The verum lcoation

    def __init__(self, PluginFolder=PluginFolder, MinionFolder=MinionFolder):
        #global PluginFolder
        self.PluginFolder = PluginFolder

        #global MinionsFolder
        self.MinionFolder = MinionFolder

        # Load enrichments database
        self.db = self.set_db()

        # LOAD HELPER FROM SAME DIRECTORY
        fp, pathname, description = imp.find_module("helper", [loc])
        self.helper = imp.load_module("helper", fp, pathname, description)

        # Save the verum location
        self.loc = loc[:-6]  # -6 removed the trailing "verum/" from the location.

        # Load the plugins Directory
        if self.PluginFolder:
            self.load_plugins()
        else:
            logging.warning("Plugin folder doesn't exist.  Plugins not configured.  Please run set_plugin_folder(<PluginFolder>) to set the plugin folder and then load_plugins() to load plugins.")


    ## PLUGIN FUNCTIONS

    def set_plugin_folder(self, PluginFolder):
        self.PluginFolder = PluginFolder

    def get_plugin_folder(self):
        return self.PluginFolder

    # Load the plugins from the plugin directory.
    def load_plugins(self):
        print "Configuring Plugin manager."
        self.plugins = PluginManager()
        if self.MinionFolder is None:
            self.plugins.setPluginPlaces([self.PluginFolder])
        else:
            self.plugins.setPluginPlaces([self.PluginFolder, self.MinionFolder])
        #self.plugins.collectPlugins()
        self.plugins.locatePlugins()
        self.plugins.loadPlugins()
        print "Plugin manager configured."

        # Loop round the plugins and print their names.
        cur = self.db.cursor()

        # Clear tables
        cur.execute("""DELETE FROM enrichments""")
        cur.execute("""DELETE FROM inputs""")
        cur.execute("""DELETE FROM storage""")
        cur.execute("""DELETE FROM score""")
        cur.execute("""DELETE FROM minion""")

        for plugin in self.plugins.getAllPlugins():
            plugin_config = plugin.plugin_object.configure()
            # Insert enrichment
            if plugin_config[0] == 'enrichment': # type
                cur.execute('''INSERT INTO enrichments VALUES (?, ?, ?, ?, ?)''', (plugin_config[2], # Name
                                                                               int(plugin_config[1]), # Enabled
                                                                               plugin_config[3], # Descripton
                                                                               plugin_config[5], # Cost
                                                                               plugin_config[6]) # Speed 
                )
                for inp in plugin_config[4]: # inputs
                    # Insert into inputs table
                    cur.execute('''INSERT INTO inputs VALUES (?,?)''', (plugin_config[2], inp))
                self.db.commit()
            elif plugin_config[0] == 'interface': # type
                cur.execute('''INSERT INTO storage VALUES (?, ?)''', (plugin_config[2], int(plugin_config[1])))
            elif plugin_config[0] == 'score':
                cur.execute('''INSERT INTO score VALUES (?, ?, ?, ?, ?)''', (plugin_config[2], # Name
                                                                               int(plugin_config[1]), # Enabled
                                                                               plugin_config[3], # Descripton
                                                                               plugin_config[4], # Cost
                                                                               plugin_config[5]) # Speed 
                )
            if plugin_config[0] == 'minion':
                plugin_config = plugin.plugin_object.configure(self)
                cur.execute('''INSERT INTO minion VALUES (?, ?, ?, ?)''', (plugin_config[2], # Name
                                                                           int(plugin_config[1]), # Enabled
                                                                           plugin_config[3], # Descripton
                                                                           plugin_config[4]) # Speed 
                )

            if plugin.name == "classify":  # Classify is a unique name.  TODO: figure out if handling multiple 'classify' plugins is necessary
                self.classify = plugin.plugin_object

#.........这里部分代码省略.........
开发者ID:theseusyang,项目名称:Verum,代码行数:103,代码来源:app.py

示例12: ModuleManager

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
class ModuleManager():
    def __init__(self, threads, kill_list, job_list):
        self.threads = threads
        self.kill_list = kill_list
        self.job_list = job_list # Running jobs
        self.pmanager = PluginManager()
        self.pmanager.setPluginPlaces(["plugins"])
        self.pmanager.collectPlugins()
        self.pmanager.locatePlugins()
        self.plugins = ['none']
        num_plugins = len(self.pmanager.getAllPlugins())
        if  num_plugins == 0:
            raise Exception("No Plugins Found!")

        plugins = []
        for plugin in self.pmanager.getAllPlugins():
            plugin.threads = threads
            self.plugins.append(plugin.name)
            plugin.plugin_object.setname(plugin.name)

            ## Check for installed binaries
            executable = ''
            try:
                settings = plugin.details.items('Settings')
                for kv in settings:
                    executable = kv[1]
                    if executable.find('/') != -1 : #Hackish "looks like a file"
                        if os.path.exists(executable):
                            logging.info("Found file: {}".format(executable))
                            break
                        else:
                            raise Exception()
                    ## TODO detect binaries not in "executable" setting
            except:
                raise Exception('[ERROR]: {} -- Binary does not exist -- {}'.format(plugin.name, executable))
            plugins.append(plugin.name)
        print "Plugins found [{}]: {}".format(num_plugins, sorted(plugins))

    def run_module(self, module, job_data_orig, tar=False, 
                   all_data=False, reads=False, meta=False, 
                   overrides=True):
        """
        Keyword Arguments:
        module -- name of plugin
        job_data -- dict of job parameters
        tar -- return tar of all output, rather than module.OUTPUT file
        all_data -- return module.OUTPUT and list of all files in self.outdir
        reads -- include files if module.OUTPUT == 'reads'
          Not recommended for large read files.

        """
        job_data = job_data_orig
        # job_data = copy.deepcopy(job_data_orig)
        # # Pass back orig file descriptor
        # try:
        #     job_data['out_report'] = job_data_orig['out_report'] 
        # except:
        #     pass
        if not self.has_plugin(module):
            raise Exception("No plugin named {}".format(module))
        plugin = self.pmanager.getPluginByName(module)
        settings = plugin.details.items('Settings')
        plugin.plugin_object.update_settings(job_data)
        if meta:
            output = plugin.plugin_object(settings, job_data, self, meta=True)
        else:
            output = plugin.plugin_object(settings, job_data, self)
        log = plugin.plugin_object.out_module.name
        if tar:
            tarfile = plugin.plugin_object.tar_output(job_data['job_id'])
            return output, tarfile, [], log
        if all_data:
            if not reads and plugin.plugin_object.OUTPUT == 'reads':
                #Don't return all files from plugins that output reads 
                data = []
            else:
                data = plugin.plugin_object.get_all_output_files()
            return output, data, log
        return output, [], log

    def output_type(self, module):
        return self.pmanager.getPluginByName(module).plugin_object.OUTPUT

    def input_type(self, module):
        return self.pmanager.getPluginByName(module).plugin_object.INPUT

    def get_short_name(self, module):
        try:
            plugin = self.pmanager.getPluginByName(module)
            settings = plugin.details.items('Settings')
            for kv in settings:
                if kv[0] == 'short_name':
                    sn = kv[1]
                    break
            return sn
        except:
            return None

    def get_executable(self, module):
        try:
#.........这里部分代码省略.........
开发者ID:leereilly,项目名称:assembly,代码行数:103,代码来源:plugins.py

示例13: gEcrit

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
class gEcrit(wx.Frame):
    """
    Editor

    This class is the entry point in the program.
    It creates all the user interface and initializes
    the required objects and classes.
    The functions that cannot go into another objects
    for diverse reasons go here.
    """

    def dummy_tr(self, tr):
        return tr

    def __init__(self, id, parent):
        """
        __init__

        Creates the user interface.
        Initializez the terminals if enabled.
        Creates the required GUI and non GUI objects.

        """
        BOTTOMPANEL_ID = 4002
        SIDEPANEL_ID = 3999

        try:
            self.presLang = gettext.translation("gEcrit", "./locale")
            self._ = self.presLang.ugettext
            self.presLang.install()
        except:
            print("Translation for local language not found.")
            self._ = self.dummy_tr

        pathname = os.path.abspath(os.path.dirname((sys.argv)[0]))  #  Finding where
        os.chdir(pathname)  #  gEcrit is running

        #Setting up the plugin envirenment

        self.general_plugins = {}
        self.passive_plugins = {}
        self.plugin_manager = PluginManager(
            categories_filter={"General": General,
                               "Passives" : Passive})

        #Sets YAPSY the plugin directory.

        self.plugin_path = os.path.join(pathname, "data", "plugins")
        self.plugin_manager.setPluginPlaces([self.plugin_path])

        self.plugin_manager.locatePlugins()
        #self.plugin_manager.collectPlugins()

        self.plugin_manager.loadPlugins()

        self.activated_plugins = Config.GetOption("ActivePlugins")

        #populating the general plugin index
        for f in self.plugin_manager.getPluginsOfCategory("General"):
            if f.plugin_object.name in self.activated_plugins:
                self.general_plugins[f.plugin_object.name] = f.plugin_object

        #the passive plugins now
        for p in self.plugin_manager.getPluginsOfCategory("Passives"):
            if p.plugin_object.name in self.activated_plugins:
                self.passive_plugins[p.plugin_object.name] = p.plugin_object

        self.id_range = []

        #getting the command line file argument
        if "gEcrit.py" not in (sys.argv)[-1]:
            target_file = os.path.normpath(os.path.realpath(sys.argv[-1]))

        #no file was provided
        else:
            target_file = None

        wx.Frame.__init__(self, parent, 1000, 'gEcrit', size=(700, 600))
        self.Bind(wx.EVT_CLOSE, self.OnQuit)

        #this object will handle layout and docking/undocking of widgets
        self.aui_manager = wx.aui.AuiManager(self)

        #creating the status bar
        self.status_bar = self.CreateStatusBar()
        self.status_bar.SetStatusText("Done")
        self.status_bar.SetFieldsCount(3)
        self.status_bar.SetId(999)
        if not Config.GetOption("StatusBar"):
            self.status_bar.Hide()

        self.menubar = MainMenu(self)
        self.SetMenuBar(self.menubar)

        #setting the application icon
        self.SetIcon(wx.Icon('icons/gEcrit.png', wx.BITMAP_TYPE_PNG))

        #this variable is incremented each time we create a StcControl
        self.text_id = 0

#.........这里部分代码省略.........
开发者ID:IseultSoft,项目名称:gEcrit,代码行数:103,代码来源:gEcrit.py

示例14: MainWindow

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]

#.........这里部分代码省略.........
        dock.setAllowedAreas(Qt.Qt.BottomDockWidgetArea)
        dock.setWidget(self._treeDissected)
        self.addDockWidget(Qt.Qt.BottomDockWidgetArea, dock)

    def __initUI(self):
        """Initialize everything for the UI"""
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self._optionsDialog.accepted.connect(self.__optionsAccepted)

        self._hexEdit.overwriteModeChanged.connect(self.setOverwriteMode)
        self._hexEdit.dataChanged.connect(self.__hexDataChanged)
        self.setCentralWidget(self._hexEdit)

        #we don't want to be able to sort by rows (keep serialized order)
        self._treeDissected.setSortingEnabled(False)

        tree_header = QTreeWidgetItem(["Name",  "Value"])
        self._treeDissected.setHeaderItem(tree_header)

        self.__createActions()
        self.__initMenus()
        self.__initToolBars()
        self.__initStatusBar()
        self.__initDockWindows()



    ###########
    # PLUGINS #
    ###########

    def __reloadPlugins(self):
        """ Load plugins """
        self._manager.locatePlugins()
        self._manager.loadPlugins()

        self.__refreshDissectors()

    def __refreshDissectors(self):
        """Refresh dissectors from the plugin manager"""
        self._availDissectors = {}
        for plugin in self._manager.getPluginsOfCategory("FormatDissectors"):
            # plugin.plugin_object is an instance of the plugin
            plug_obj = plugin.plugin_object
            self._availDissectors[plug_obj.name] = plug_obj

        # if we have a dissector loaded, reload it from the dict of
        # available dissectors
        if self._dissector and self._dissector.name in self._availDissectors:
            self._dissector = self._availDissectors[self._dissector.name]
        else:
            self._dissector = None



    ############
    # SETTINGS #
    ############

    def readSettings(self):
        """Reload all settings for this application from storage"""
        settings = QtCore.QSettings()
        pos = settings.value('pos', QtCore.QPoint(200, 200)).toPoint()
        size = settings.value('size', QtCore.QSize(610, 460)).toSize()
        self.move(pos)
        self.resize(size)
开发者ID:JordanMilne,项目名称:Parslither,代码行数:70,代码来源:mainwindow.py

示例15: HandlerManager

# 需要导入模块: from yapsy.PluginManager import PluginManager [as 别名]
# 或者: from yapsy.PluginManager.PluginManager import locatePlugins [as 别名]
class HandlerManager(QThread):

    # 返回命令执行结果
    # int:  0  -- 返回PlainText
    #       1  -- 返回RichText
    # str:  结果
    outSignal = pyqtSignal(int, str)

    def __init__(self):
        super(HandlerManager, self).__init__()

        # 创建工作队列,用户输入的命令按照顺序put进该队列
        # 由CommandHandler在后台逐个处理
        self.workQueue = Queue()

        # 初始化插件功能
        self.initPlugin()

    def __del__(self):
        self.wait()

    def initPlugin(self):
        '''
        启动插件管理器,获取插件列表
        '''

        # 创建插件管理器
        self.pluginManager = PluginManager()

        # 设置插件接口为 DPlugin,所有插件必须继承categories.DPlugin
        self.pluginManager.setCategoriesFilter({"DPlugin": DPlugin})

        # 设置插件目录
        self.pluginManager.setPluginPlaces(['plugins'])

        # 加载插件到内存
        self.pluginManager.locatePlugins()
        self.pluginManager.loadPlugins()

    def getAllPlugins(self):
        '''获取插件列表'''
        return self.pluginManager.getPluginsOfCategory('DPlugin')

    def activateAllPlugins(self):
        '''使能所有插件'''
        for plugin in self.pluginManager.getPluginsOfCategory('DPlugin'):
            plugin.plugin_object.activate()

    def deactivateAllPlugins(self):
        '''禁用所有插件'''
        for plugin in self.pluginManager.getPluginsOfCategory('DPlugin'):
            plugin.plugin_object.deactivate()

    def activatePlugin(self, name):
        '''使能特定插件'''
        self.pluginManager.activatePluginByName(name, category="DPlugin")

    def deactivatePlugin(self, name):
        '''使能特定插件'''
        self.pluginManager.deactivatePluginByName(name, category="DPlugin")

    def processInput(self, userInput):
        '''将命令放入队列'''
        self.workQueue.put((False, userInput))

    def processFile(self, filepath):
        '''将待处理文件放入队列'''
        self.workQueue.put((True, filepath))

    def run(self):
        '''不断从Queue中获取数据,然后执行解析命令'''
        while True:
            isFile, userInput = self.workQueue.get()
            if isFile:
                self.execFile(userInput)
            else:
                self.execCommand(userInput, None)

    def execCommand(self, userInput, currentFile):
        '''
        解析命令
        '''
        if not len(userInput) or userInput.startswith('#'):
            return

        # 命令回显
        self.writeCommand(userInput)

        # 命令分割
        command, *params = userInput.split(maxsplit=1)

        if command == 'source':
            if len(params) == 1:
                filepath = params[0]
                if not os.path.isabs(filepath):
                    basepath = os.path.dirname(currentFile)
                    filepath = os.path.normpath(filepath)
                    filepath = os.path.join(basepath, filepath)
                self.execFile(filepath)
            else:
#.........这里部分代码省略.........
开发者ID:lijg,项目名称:DebugTool,代码行数:103,代码来源:CommandHandler.py


注:本文中的yapsy.PluginManager.PluginManager.locatePlugins方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。