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


Python path.insert函数代码示例

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


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

示例1: _install_updates

 def _install_updates(self):
     """
     Installs updated modules. 
     
     Checks the updates directory for new versions of one of the modules listed in self.UPDATE_MODULES and reloads the modules. Version check is performed by comparing the VERSION variable stored in the module.
     """
     updated_modules = 0
     if path.exists(self.UPDATE_DIR):
         sys_path.insert(0, self.UPDATE_DIR)
         for m in self.UPDATE_MODULES:
             modulefile = path.join(self.UPDATE_DIR, "%s%spy" % (m.__name__, extsep))
             if path.exists(modulefile):
                 v_dict = {'VERSION': -1}
                 with open(modulefile) as f:
                     for line in f:
                         if line.startswith('VERSION'):
                             exec line in v_dict
                             break
                     else:
                         logger.error("Could not find VERSION string in file %s!" % modulefile) 
                         continue
                 if v_dict['VERSION'] > m.VERSION:
                     logging.info("Reloading Module '%s', current version number: %d, new version number: %d" % (m.__name__, v_dict['VERSION'], m.VERSION))
                     reload(m)
                     if m == cachedownloader and self.cachedownloader != None:
                         self.__install_cachedownloader()
                     updated_modules += 1
                 else:
                     logging.info("Not reloading Module '%s', current version number: %d, version number of update file: %d" % (m.__name__, m.VERSION, v_dict['VERSION']))
             else:
                 logging.info("Skipping nonexistant update from" + path.join(self.UPDATE_DIR, "%s%spy" % (m.__name__, extsep)))
     return updated_modules
开发者ID:cuckoohello,项目名称:advancedcaching,代码行数:32,代码来源:core.py

示例2: determineT

def determineT():
    def pystones(*args, **kwargs):
        from warnings import warn
        warn("Python module 'test.pystone' not available. Will assume T=1.0")
        return 1.0, "ignored"

    pystonesValueFile = expanduser('~/.seecr-test-pystones')
    if isfile(pystonesValueFile):
        age = time() - stat(pystonesValueFile).st_mtime
        if age < 12 * 60 * 60:
            return float(open(pystonesValueFile).read())

    temppath = []
    while len(path) > 0:
        try:
            if 'test' in sys.modules:
                del sys.modules['test']
            from test.pystone import pystones

            break
        except ImportError:
            temppath.append(path[0])
            del path[0]
    for temp in reversed(temppath):
        path.insert(0, temp)
    del temppath
    T, p = pystones(loops=50000)
    try:
        with open(pystonesValueFile, 'w') as f:
            f.write(str(T))
    except IOError:
        pass
    return T
开发者ID:seecr,项目名称:seecr-test,代码行数:33,代码来源:timing.py

示例3: _install_updates

 def _install_updates(self):
     updated_modules = 0
     if path.exists(self.UPDATE_DIR):
         sys_path.insert(0, self.UPDATE_DIR)
         for m in self.UPDATE_MODULES:
             modulefile = path.join(self.UPDATE_DIR, "%s%spy" % (m.__name__, extsep))
             if path.exists(modulefile):
                 v_dict = {"VERSION": -1}
                 with open(modulefile) as f:
                     for line in f:
                         if line.startswith("VERSION"):
                             exec line in v_dict
                             break
                 if v_dict["VERSION"] > m.VERSION:
                     pass  # logging.info("Reloading Module '%s', current version number: %d, new version number: %d" % (m.__name__, v_dict['VERSION'], m.VERSION))
                     reload(m)
                     updated_modules += 1
                 else:
                     logging.info(
                         "Not reloading Module '%s', current version number: %d, version number of update file: %d"
                         % (m.__name__, v_dict["VERSION"], m.VERSION)
                     )
             else:
                 logging.info(
                     "Skipping nonexistant update from" + path.join(self.UPDATE_DIR, "%s%spy" % (m.__name__, extsep))
                 )
     return updated_modules
开发者ID:ChrisPHL,项目名称:advancedcaching,代码行数:27,代码来源:core.py

示例4: extension

def extension(buildout):
    def setup(name, *args, **kw):
        buildout["buildout"].setdefault("package-name", name)

    # monkey-patch `setuptools.setup` with the above...
    import setuptools

    original = setuptools.setup
    setuptools.setup = setup

    # now try to import `setup.py` from the current directory, extract
    # the package name using the helper above and set `package-name`
    # in the buildout configuration...
    here = abspath(curdir)
    path.insert(0, here)
    import setup

    # mention `setup` again to make pyflakes happy... :p
    setup

    # reset `sys.path` and undo the above monkey-patch
    path.remove(here)
    setuptools.setup = original

    # if there's a `setup.py` in the current directory
    # we also want to develop this egg...
    # print buildout['buildout']
    buildout["buildout"].setdefault("develop", ".")

    return buildout
开发者ID:pombredanne,项目名称:buildout.packagename,代码行数:30,代码来源:__init__.py

示例5: submit

    def submit(self, depend=None):
        self.reservations = ["host.processors=1+"]

        # add license registration
        for each in self.licenses:
            self.reservations.append("license.%s" % each)

        from sys import path

        path.insert(0, pipe.apps.qube().path("qube-core/local/pfx/qube/api/python/"))
        import qb

        # print dir(qb)
        self.qb = qb.Job()
        self.qb["name"] = self.name
        self.qb["prototype"] = "cmdrange"
        self.qb["package"] = {
            #            'cmdline' : 'echo "Frame QB_FRAME_NUMBER" ; echo $HOME ; echo $USER ; cd ; echo `pwd` ; sleep 10',
            "cmdline": self.cmd,
            "padding": self.pad,
            "range": str(self.range())[1:-1],
        }
        self.qb["agenda"] = qb.genframes(self.qb["package"]["range"])
        self.qb["cpus"] = self.cpus
        self.qb["hosts"] = ""
        self.qb["groups"] = self.group
        self.qb["cluster"] = "/pipe"
        self.qb["priority"] = self.priority
        self.qb["reservations"] = ",".join(self.reservations)
        self.qb["retrywork"] = self.retry
        self.qb["retrywork_delay"] = 15
        self.qb["retrysubjob"] = self.retry
        self.qb["flags"] = "auto_wrangling,migrate_on_frame_retry"

        return qb.submit(self.qb)[0]["id"]
开发者ID:hradec,项目名称:pipeVFX,代码行数:35,代码来源:qube.py

示例6: __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

示例7: __init__

 def __init__(self, len_argv=len(argv)):
     path.insert(0, os.path.join('static', 'modules'))
     if len_argv > 1:
         def few_arg_test(func, num1, num2):
             if len_argv > num1:
                 start_module_function = getattr(import_module('functions'), func)
                 start_module_function(icy)
             else:
                 raise SystemExit('\nWARNING "{0}" requires {1} arguments,'\
                 '\nyou have given me {2} !\n'.format(lenny, num2, len(icy)))
         dash_clash = lambda crash: '{0} -{0} --{0} {0[0]} -{0[0]} --{0[0]}'\
                                                       .format(crash).split()
         lenny = argv[1]
         icy   = argv[2:]
         if lenny in dash_clash('replace'):
             few_arg_test('replace_str', 3, 2)
         if lenny in dash_clash('new'):
             few_arg_test('create_new_post', 2, 1)
         if lenny in dash_clash('format'):
             few_arg_test('format_post', 2, 1)
         if lenny in dash_clash('optimize'):
             few_arg_test('optimize_modules', 1, 0)
     else:
         from blogfy import GenerateBlog
         GenerateBlog()
开发者ID:kleutchit,项目名称:dotfiles,代码行数:25,代码来源:generate.py

示例8: __init__

  def __init__(self, path=None):
    self.__dict__ = self.__state
    if not path:
      if not self.path:
        raise KitError('No path specified')

    else:
      path = abspath(path)

      if self.path and path != self.path:
        raise KitError('Invalid path specified: %r' % path)

      elif not self.path:
        self.path = path

        with open(path) as handle:
          self.config = load(handle)

        if self.root not in sys_path:
          sys_path.insert(0, self.root)

        for module in self._modules:
          __import__(module)

        # Session removal handlers
        task_postrun.connect(_remove_session)
        request_tearing_down.connect(_remove_session)
开发者ID:daqing15,项目名称:kit,代码行数:27,代码来源:base.py

示例9: test

def test(user, data):
    path.insert(0, "src")

    from utils import *
    from globals import *

    i = 0
    (conn, cursor) = getDbCursor(getUserDb(user))

    print data
    while True:
        if str(i) not in data:
            break

        if i == 0 and data[str(i)].lower() == "yes":
            cursor.execute('INSERT into SPECIAL_FLAG values("%s", "%s");' % (user, SF_PROGRAMMED))
        elif i == 1 and data[str(i)].lower() == "yes":
            cursor.execute('INSERT into SPECIAL_FLAG values("%s", "%s");' % (user, SF_SCHEME))
        elif i == 2 and data[str(i)].lower() == "yes":
            cursor.execute('INSERT into SPECIAL_FLAG values("%s", "%s");' % (user, SF_RECURSION))

        i += 1

    conn.commit()
    cursor.close()
开发者ID:darrenkuo,项目名称:SP,代码行数:25,代码来源:test.py

示例10: abrir_factura

 def abrir_factura(self, tv, path, view_column):
     model = tv.get_model()
     puid = model[path][-1]
     if puid:
         objeto = pclases.getObjetoPUID(puid)
         if isinstance(objeto, pclases.FacturaVenta):
             fra = objeto 
             try:
                 import facturas_venta
             except ImportError:
                 from os.path import join as pathjoin
                 from sys import path
                 path.insert(0, pathjoin("..", "formularios"))
                 import facturas_venta
             ventana = facturas_venta.FacturasVenta(fra, self.usuario)
         elif isinstance(objeto, pclases.Cliente):
             cliente = objeto 
             try:
                 import clientes
             except ImportError:
                 from os.path import join as pathjoin
                 from sys import path
                 path.insert(0, pathjoin("..", "formularios"))
                 import clientes
             ventana_clientes = clientes.Clientes(cliente, self.usuario)
开发者ID:pacoqueen,项目名称:upy,代码行数:25,代码来源:up_consulta_facturas.py

示例11: _load

    def _load(self, project):
        Repository._load(self, project)
        ppath = project.config.get(self.name, 'python-path')
        if ppath:
            from sys import path

            if ppath not in path:
                path.insert(0, ppath)
开发者ID:lelit,项目名称:tailor,代码行数:8,代码来源:bzr.py

示例12: __call__

    def __call__(self, parser, args, values, option = None):
        args.profile = values

        global profile
        # append profiles subdir to the path variable, so we can import dynamically the profile file
        path.insert(0, "./profiles")
        # import a module with a dynamic name
        profile = __import__(args.profile)
开发者ID:mylk,项目名称:mass-geocoder,代码行数:8,代码来源:massgeocode.py

示例13: loadObject

 def loadObject( self, obj_type, obj_name, build_var ):
   path.insert( 1, self.garden_dir + obj_type.lower() + "s" )
   obj_name = obj_type + obj_name
   __import__( obj_name )
   if build_var:
     obj = getattr( sys.modules[ "%s" % obj_name ], "%s" % obj_name )( build_var )
   else:
     obj = getattr( sys.modules[ "%s" % obj_name ], "%s" % obj_name )()
   return obj
开发者ID:politeauthority,项目名称:garden_pi,代码行数:9,代码来源:MVC.py

示例14: test_rewrite_pyc_check_code_name

    def test_rewrite_pyc_check_code_name(self):
        # This one is adapted from cpython's Lib/test/test_import.py
        from os import chmod
        from os.path import join
        from sys import modules, path
        from shutil import rmtree
        from tempfile import mkdtemp

        code = """if 1:
            import sys
            code_filename = sys._getframe().f_code.co_filename
            module_filename = __file__
            constant = 1
            def func():
                pass
            func_filename = func.func_code.co_filename
            """

        module_name = "unlikely_module_name"
        dir_name = mkdtemp(prefix="pypy_test")
        file_name = join(dir_name, module_name + ".py")
        with open(file_name, "wb") as f:
            f.write(code)
        compiled_name = file_name + ("c" if __debug__ else "o")
        chmod(file_name, 0777)

        # Setup
        sys_path = path[:]
        orig_module = modules.pop(module_name, None)
        assert modules.get(module_name) == None
        path.insert(0, dir_name)

        # Test
        import py_compile

        py_compile.compile(file_name, dfile="another_module.py")
        __import__(module_name, globals(), locals())
        mod = modules.get(module_name)

        try:
            # Ensure proper results
            assert mod != orig_module
            assert mod.module_filename == compiled_name
            assert mod.code_filename == file_name
            assert mod.func_filename == file_name
        finally:
            # TearDown
            path[:] = sys_path
            if orig_module is not None:
                modules[module_name] = orig_module
            else:
                try:
                    del modules[module_name]
                except KeyError:
                    pass
            rmtree(dir_name, True)
开发者ID:cimarieta,项目名称:usp,代码行数:56,代码来源:test_app.py

示例15: run

def run(p):
    global app, render

    parent_folder = abspath('..')
    if parent_folder not in path:
        path.insert(0, parent_folder)

    app = web.application(urls, globals(), True)
    render = web.template.render(join(p, 'templates/'))
    app.run()
开发者ID:darrenkuo,项目名称:the_clustering_experiment,代码行数:10,代码来源:server.py


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