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


Python path.append函数代码示例

本文整理汇总了Python中sys.path.append函数的典型用法代码示例。如果您正苦于以下问题:Python append函数的具体用法?Python append怎么用?Python append使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: _config_check

def _config_check():
    from message import Messager
    
    from sys import path
    from copy import deepcopy
    from os.path import dirname
    # Reset the path to force config.py to be in the root (could be hacked
    #       using __init__.py, but we can be monkey-patched anyway)
    orig_path = deepcopy(path)
    # Can't you empty in O(1) instead of O(N)?
    while path:
        path.pop()
    path.append(path_join(abspath(dirname(__file__)), '../..'))
    # Check if we have a config, otherwise whine
    try:
        import config
        del config
    except ImportError, e:
        path.extend(orig_path)
        # "Prettiest" way to check specific failure
        if e.message == 'No module named config':
            Messager.error(_miss_config_msg(), duration=-1)
        else:
            Messager.error(_get_stack_trace(), duration=-1)
        raise ConfigurationError
开发者ID:TsujiiLaboratory,项目名称:stav,代码行数:25,代码来源:server.py

示例2: parse_configuration

def parse_configuration(root):
    """Parses an XML document representing the configuration of the
    logwrap utility.  The document is parsed and two items are
    returned: the error handler used to process errors and a list of
    encapsulators for the event framework.
    """

    encapsulators = []

    config = get_child_elements("logWrap", root, first=1)
    if config == None:
        raise BuilderError, "You must have an outer logWrap element"

    for node in get_child_elements("handlerDirectory", config):
        dir = interpolate_text(node.getAttribute("dir"), environ)
        if not dir:
            raise BuilderError, "handlerDirectory requires a dir attribute"
        path.append(str(dir))

    error_handler = build_error_handler(config)
    if error_handler:
        error_handler = ErrorHandlerAdapter(error_handler)

    for node in get_child_elements("logEncapsulator", config):
        encapsulators.append(parse_logEncapsulator(node))

    if len(encapsulators) == 0:
        raise BuilderError, "You must configure at least one log encapsulator"

    return error_handler, encapsulators
开发者ID:pkazmier,项目名称:logwrap,代码行数:30,代码来源:Builder.py

示例3: main

def main(args):
    argp = _argparser().parse_args(args[1:])

    try:
        # At first, try using global installs
        import simstring
        del simstring
    except ImportError:
        # If that fails, try our local version
        sys_path.append(SIMSTRING_PY_DIR)
        try:
            import simstring
            del simstring
        except ImportError:
            from sys import stderr
            print('ERROR: Failed to import SimString, did you run make to '
                    'build it or install it globally?', file=stderr)
            return -1

    if not argp.simstring_dbs:
        raise NotImplementedError
    else:
        db_paths = argp.resources

    tokens = [unicode(l, encoding=argp.input_encoding).rstrip('\n')
            for l in argp.input]
    for token, repr in _token_reprs(tokens, db_paths, verbose=argp.verbose):
        repr_tsv = '\t'.join(str(r) for r in repr)
        # Assume that the user wants the output/input to have the same encoding
        print((u'{}\t{}'.format(token, repr_tsv)).encode(argp.input_encoding),
                file=argp.output)

    return 0
开发者ID:ninjin,项目名称:fader,代码行数:33,代码来源:tokenreprs.py

示例4: instantiatePlugins

    def instantiatePlugins(self):
        """
        Looks for plugins classes and instantiates them

        Returns
        -------
        plg : list
            A list of class instances, one for each plugin found.
        grp : list
            A list of the plugins groups.
        """
        # TODO: Implement the plugin classes: Input, Output, Analysis and use
        #       them to place widgets on the screen
        PLUGINS_DIR = 'Plugins'
        VALID_CLASSES = ['Input', 'Analysis']
        plugins_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), PLUGINS_DIR)
        plugins_files = glob(os.path.join(plugins_folder, '*.py'))
        plugins_list = [f[:-3] for _, f in [os.path.split(p) for p in plugins_files]]
        path.append(plugins_folder)  # Add plugins path to PYTHONPATH

        plg = []
        grp = set()
        for v in plugins_list:
            try:
                v = getattr(import_module(v), v)
            except ImportError as e:
                print 'TODO: handle this error: ' + e.message
                pass
            else:
                inst = v()
                if VALID_CLASSES.count(inst.pluginClass) == 0:
                    continue
                plg.append(inst)
                grp.add(inst.pluginGroup)
        return plg, list(grp)
开发者ID:VIVAUVA,项目名称:GISque,代码行数:35,代码来源:TkSAR.py

示例5: run

    def run(self, process, action_value, *args, **kwargs):
        """
        Will process the information passed in action_value.
        """
        python_path = format_value(process, "path", default_value=self.python_path)
        if not exists(python_path):
            raise ValueError("The directory [%s] not exist." % self.python_path)
        path_exist = python_path in path
        try:
            if not path_exist: path.append(python_path)

            # Check the module
            module = format_value(process, "module", default_value=None)
            if module is None: raise ValueError("The module was not set in %s that use the connection [%s]" % (process["tag"], process["connection_name"]))
            if not (exists(join(python_path, module + ".py")) or exists(join(python_path, module + ".pyc"))):
                raise ValueError("The module [%s] not exist in the path [%s]" % (module, python_path))
            class_name = format_value(process, "class", default_value=None)
            method = format_value(process, "method", default_value="run")
            module_ref = __import__(module, fromlist=None if class_name is None else [class_name, ])
            instance = (None, 1, "Was not implemented yet!")
            if class_name:
                class_ref = getattr(module_ref, class_name)()
                instance = getattr(class_ref, method)(process, action_value, *args, **kwargs)
            else:
                instance = getattr(module_ref, method)(process, action_value, *args, **kwargs)
            return instance
        except Exception, e:
            return (None, settings.SYSTEM_ERROR, e)
开发者ID:Ozahata,项目名称:procsync,代码行数:28,代码来源:python.py

示例6: process

def process(inputFile, outputFile):
    ''' Reads a block log CSV, cleans the comment, reorders the output and
    writes it to disk according to outputFile. Please be aware that, if
    writing permissions are given for outputFile, it will blindly overwrite
    everything you love.
    '''
    import csv
    from sys import path
    path.append("./WikiCodeCleaner")
    try:
        from WikiCodeCleaner.clean import clean as cleanWikiCode
    except ImportError:
        # Ubuntu 12.04's Python 3.2.3 behaves differently:
        from clean import clean as cleanWikiCode
    ignoredBlocksCount = 0

    with inputFile:
        logReader = csv.reader(inputFile, delimiter='\t', quotechar='"')
        logWriter = csv.writer(outputFile, delimiter='\t',
                                   quotechar='|', quoting=csv.QUOTE_MINIMAL)

        for [comment, userId, userName, timestamp, blockedUserName] in logReader:
            comment = comment.lower()
            cleanedComment = cleanWikiCode(comment).strip()
            if isCommentOfInterest(cleanedComment):
                logWriter.writerow([timestamp,
                                    blockedUserName,
                                    cleanedComment,
                                    userId,
                                    userName])
            else:
                ignoredBlocksCount += 1
    print('[I] Ignored %i comments' % ignoredBlocksCount)
开发者ID:0nse,项目名称:WikiParser,代码行数:33,代码来源:BlockLogPostProcessing.py

示例7: loadConfig

 def loadConfig(self):
     # if local configuration file exists use it
     self.FCONFIG = ('./etc/timekpr.conf' if isfile('./etc/timekpr.conf') else '/etc/timekpr.conf')
     if not isfile(self.FCONFIG):
         exit(_("Error: timekpr configuration file %s does not exist.") % self.FCONFIG)
     self.VAR = loadVariables(self.FCONFIG)
     if self.VAR['DEVACTIVE']:
         from sys import path
         path.append('.')
     self.logkpr('Loaded Configuration from %s' % self.FCONFIG, 1)
     self.logkpr('Variables: GRACEPERIOD: %s POLLTIME: %s LOCKLASTS: %s' % (\
         self.VAR['GRACEPERIOD'], self.VAR['POLLTIME'], self.VAR['LOCKLASTS']))
     self.logkpr('Debuging: DEBUGME: %s CLOCKSPEED: %s CLOCKTIME: %s' % (\
         self.VAR['DEBUGME'], self.VAR['CLOCKSPEED'], self.VAR['CLOCKTIME']))
     self.logkpr('Directories: LOGFILE: %s TIMEKPRDIR: %s TIMEKPRWORK: %s TIMEKPRSHARED: %s' % (\
         self.VAR['LOGFILE'], self.VAR['TIMEKPRDIR'], self.VAR['TIMEKPRWORK'], self.VAR['TIMEKPRSHARED']))
     #Check if all directories exists, if not, create it
     if not isdir(self.VAR['TIMEKPRDIR']):
         mkdir(self.VAR['TIMEKPRDIR'])
     if not isdir(self.VAR['TIMEKPRWORK']):
         makedirs(self.VAR['TIMEKPRWORK'])
     #set clockspeed
     if self.VAR['CLOCKSPEED'] != 1:
         self.logkpr('setting clockspeed to %s' % self.VAR['CLOCKSPEED'])
         clock.setSpeed(self.VAR['CLOCKSPEED'])
     if self.VAR['CLOCKTIME'] != '':
         self.logkpr('setting clock time to %s' % strDateTime2tuple(self.VAR['CLOCKTIME']))
         clock.setTime(strDateTime2tuple(self.VAR['CLOCKTIME']))
开发者ID:captainnhunt,项目名称:watchout,代码行数:28,代码来源:timekpr.py

示例8: application

def application(environ, start_response):
    peticiones = environ['REQUEST_URI'].split('/')
    peticiones.pop(0)
    cantidad = len(peticiones)
    if cantidad == 3:
        modulo, modelo, recurso = peticiones
        arg = ''
    elif cantidad == 4:
        modulo, modelo, recurso, arg = peticiones
    else:
        modulo = 'users'
        modelo = 'user'
        recurso = 'index'
        arg = ''

    controller_name = '%sController' % modelo.capitalize()
    from sys import path
    path.append(environ['SCRIPT_FILENAME'].replace('frontcontroller.py', ''))
    exec ('from modules.%s.controllers.%s import %s' %
        (modulo, modelo, controller_name))
    controller = locals()[controller_name](recurso, arg, environ)
    output = controller.output
    start_response('200 OK', [('Content-Type',
        'text/html; charset=UTF-8')])
    return output
开发者ID:leoelcoder,项目名称:python-mvc-lite,代码行数:25,代码来源:frontcontroller.py

示例9: main

def main():
    fusil_dir = dirname(__file__)
    sys_path.append(fusil_dir)

    # Disable xmlrpclib backport to avoid a bug in the unit tests
    from ufwi_rpcd.python import backportXmlrpclib
    backportXmlrpclib.done = True

    # Test documentation in doc/*.rst files
    testDoc('tests/try_finally.rst')

    # Test documentation of some functions/classes
    testModule("ufwi_rpcd.common.human")
    testModule("ufwi_rpcd.common.network")
    testModule("ufwi_rpcd.common.tools")
    testModule("ufwi_rpcd.common.transport")
    testModule("ufwi_rpcd.common.error")
    testModule("ufwi_rpcd.common.defer")
    testModule("ufwi_rpcd.common.ssl.checker")
    testModule("ufwi_rpcd.common.namedlist")
    testModule("ufwi_rpcd.common.process")
#    testModule("ufwi_rpcd.qt.tools")
    testModule("tools.ufwi_rpcd_client", "tools/ufwi_rpcd_client")
    # __import__('tools.ufwi_rpcd_client') compiles the Python file
    # to tools/ufwi_rpcd_clientc
    unlink("tools/ufwi_rpcd_clientc")
开发者ID:maximerobin,项目名称:Ufwi,代码行数:26,代码来源:doc_test.py

示例10: init

    def init(self, *args, **kwargs):
        super(RPlugins, self).init(*args, **kwargs)

        if "rplugins" not in self.config:
            raise ConfigError("Remote Plugins not configured!")

        for param in ("path",):
            if param not in self.config["rplugins"]:
                raise ConfigError("Remote Plugins not configured! Missing: {0}".format(repr(param)))

        self.data.init(
            {
                "rplugins": {
                    "allowed": {},
                    "pending": {},
                    "enabled": {},
                }
            }
        )

        rplugins_path = self.config["rplugins"]["path"]
        if not path_exists(rplugins_path):
            mkdir(rplugins_path)

        rplugins_init_py = path_join(rplugins_path, "__init__.py")
        if not path_exists(rplugins_init_py):
            with open(rplugins_init_py, "w") as f:
                f.write("")

        if rplugins_path not in module_search_path:
            module_search_path.append(rplugins_path)

        Commands().register(self)
        RPluginsCommands().register(self)
开发者ID:prologic,项目名称:kdb,代码行数:34,代码来源:rplugins.py

示例11: startMenu

def startMenu():
    py.init()
    v.screen = py.display.set_mode((920, 630), py.DOUBLEBUF)
    buttons = py.sprite.Group()
    buttons.add(mapMenuItems.button("New Map", (460, 270), 50, (255, 255, 0), (0, 0, 255), "../Resources/Fonts/RunicSolid.ttf", "NM", True, (220, 50)))
    buttons.add(mapMenuItems.button("Load Map", (460, 360), 50, (255, 255, 0), (0, 0, 255), "../Resources/Fonts/RunicSolid.ttf", "LM", True, (220, 50)))
    
    texts = py.sprite.Group()
    texts.add(mapMenuItems.textLabel("Legend Of Aiopa RPG", (460, 150), (255, 0, 255), "../Resources/Fonts/RunicSolid.ttf", 50, variable = False, centred = True))
    texts.add(mapMenuItems.textLabel("Map Editor", (460, 200), (200, 0, 200), "../Resources/Fonts/RunicSolid.ttf", 40, variable = False, centred = True))
    
    v.textNum = 1
    while True:
        py.event.pump()
        v.events = []
        v.events = py.event.get()
        v.screen.fill((0, 255, 255))
        texts.update()
        buttons.update()
        py.display.flip()
        
        for event in v.events:
            if event.type == py.MOUSEBUTTONDOWN:
                for b in buttons:
                    if b.pressed():
                        if b.ID == "NM":
                            #setup()
                            npcEdit.createNPC()
                        if b.ID == "LM":
                            from sys import path
                            path.append('../Saves')
                            import mapFile  # @UnresolvedImport
                            v.totalMap = mapFile.map
                            load()
开发者ID:Lightning3105,项目名称:Legend-Of-Aiopa-RPG,代码行数:34,代码来源:MapEditor.py

示例12: run

def run(doc_id, sent_id, words, lemmas, poses, ners, dep_paths, dep_parents, wordidxs, relation_id, wordidxs_1, wordidxs_2):
  try:
    import ddlib
  except:
    import os
    DD_HOME = os.environ['DEEPDIVE_HOME']
    from sys import path
    path.append('%s/ddlib' % DD_HOME)
    import ddlib

  obj = dict()
  obj['lemma'] = []
  obj['words'] = []
  obj['ner'] = []
  obj['pos'] = []
  obj['dep_graph'] = []
  for i in xrange(len(words)):
      obj['lemma'].append(lemmas[i])
      obj['words'].append(words[i])
      obj['ner'].append(ners[i])
      obj['pos'].append(poses[i])
      obj['dep_graph'].append(
          str(int(dep_parents[i])) + "\t" + dep_paths[i] + "\t" + str(i))
  word_obj_list = ddlib.unpack_words(
      obj, lemma='lemma', pos='pos', ner='ner', words='words', dep_graph='dep_graph')
  gene_span = ddlib.get_span(wordidxs_1[0], len(wordidxs_1))
  pheno_span = ddlib.get_span(wordidxs_2[0], len(wordidxs_2))
  features = set()
  for feature in ddlib.get_generic_features_relation(word_obj_list, gene_span, pheno_span):
    features.add(feature)
  for feature in features:
    yield doc_id, relation_id, feature
开发者ID:robinjia,项目名称:dd-genomics,代码行数:32,代码来源:pair_features.py

示例13: __init__

    def __init__(self, keyspace_name, table_name, record_schema, cassandra_session, replication_strategy=None):

        title = '%s.__init__' % self.__class__.__name__
    
    # construct fields model
        from jsonmodel.validators import jsonModel
        self.fields = jsonModel(self._class_fields)

    # validate inputs
        input_fields = {
            'keyspace_name': keyspace_name,
            'table_name': table_name,
            'record_schema': record_schema,
            'replication_strategy': replication_strategy
        }
        for key, value in input_fields.items():
            if value:
                object_title = '%s(%s=%s)' % (title, key, str(value))
                self.fields.validate(value, '.%s' % key, object_title)

    # validate cassandra session
        from sys import path as sys_path
        sys_path.append(sys_path.pop(0))
        from cassandra.cluster import Session
        sys_path.insert(0, sys_path.pop())
        if not isinstance(cassandra_session, Session):
            raise ValueError('%s(cassandra_session) must be a cassandra.cluster.Session datatype.' % title)
        self.session = cassandra_session
开发者ID:collectiveacuity,项目名称:labPack,代码行数:28,代码来源:cassandra.py

示例14: addpathImp

 def addpathImp(path):
     if not isdir(path):
         return
     if path not in SYSPATH:
         SYSPATH.append(path)
     for x in listdir(path):
         addpathImp("%s/%s" % (path, x))
开发者ID:pasha0220,项目名称:gosinfo,代码行数:7,代码来源:main.py

示例15: load_environment

def load_environment(global_conf, app_conf):
    """Configure the Pylons environment via the ``pylons.config``
    object
    """
    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = dict(root=root,
                 controllers=os.path.join(root, 'controllers'),
                 static_files=os.path.join(root, 'public'),
                 templates=[os.path.join(root, 'templates')])

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='OnDeafTweers_web', paths=paths)

    config['routes.map'] = make_map()
    config['pylons.app_globals'] = app_globals.Globals()
    config['pylons.h'] = OnDeafTweers_web.lib.helpers

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8', default_filters=['escape'],
        imports=['from webhelpers.html import escape'])

    # Setup the SQLAlchemy database engine
    engine = engine_from_config(config, 'sqlalchemy.')
    init_model(engine)

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)

    # Make sure we've got the lib directory in sys.path
    importpath.append(os.path.join(root, 'lib'))
开发者ID:1stvamp,项目名称:OnDeafTweers,代码行数:35,代码来源:environment.py


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