• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python path.insert函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: update_python_environment_with

def update_python_environment_with(module_path):
	from os.path import dirname
	module_folder = dirname(module_path)
	from sys import path
	if not (module_folder in path): path.insert(0, module_folder)
	from os import environ, pathsep, putenv
	python_path = pathsep.join(path)
	environ["PYTHONPATH"] = python_path
	putenv("PYTHONPATH", python_path)
	return
开发者ID:mystilleef,项目名称:scribes,代码行数:10,代码来源:Utils.py


示例17: getPluginHelp

def getPluginHelp( data ):
    plugin, params = data.module[0], data.module[1:]
    logger.info('Loading "%s" module help' % plugin)
    from sys import path
    path.insert(0, "./modules")
    plugin_name = "plugin_"+plugin
    plugin = __import__(plugin_name, globals(), locals(), ['object'], -1)
    try:
        plugin.help(params)
    except AttributeError as err:
        logger.error('\nIt is not possible to show help for "%s" module. ERROR:\n\t%s\n' % (plugin_name, err) )
开发者ID:thefatalist,项目名称:cmdExec,代码行数:11,代码来源:cmdExec.py


示例18: classFactory

    def classFactory(class_name):
        class_lower_name = class_name.lower()

        if class_name in SUBTITLE_SITE_LIST:
            engines_path = os.path.dirname(__file__)
            if engines_path not in sys_path:
                sys_path.insert(0, engines_path)

            subtitle_module = import_module(class_lower_name)
            subtitle_class = getattr(subtitle_module, class_name)

            return subtitle_class()
开发者ID:alon7,项目名称:RemoteDownloader,代码行数:12,代码来源:subtitlesite.py


示例19: evalQuiz

def evalQuiz(user, data):
    f = open(join(quiz_requests, '%s.quiz-%s.%d' % 
                  (user, data['page'].split('-')[-1], 
                   int(time() * 1000))), 'w')
    f.write(str(data))
    f.close()

    path.insert(0, join(course_material, str(data['page'])))
    #test_mod = __import__(join(course_material, str(data['page']), 'test.py'))
    import test as test_mod
    test_mod.test(user, data)

    del test_mod
开发者ID:darrenkuo,项目名称:SICP,代码行数:13,代码来源:quiz.py


示例20: dumps_json

 def dumps_json(self, obj):
     '将列表,解析为json的字符串'
     try:
         from json import dumps
     except ImportError:
         '''由于py2.6以上才内置了JSON模块,
                             故如果没有内置则采用第三方模块:
         Contact mailto:[email protected]
         '''
         path.insert(0, self.dcc_def.const.PLUS_PATH)
         from minjson import write as dumps
         
     return dumps(obj)
开发者ID:ganmao,项目名称:Ocs-Test-Suite,代码行数:13,代码来源:dcc_engine.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python platform.startswith函数代码示例发布时间:2022-05-27
下一篇:
Python path.extend函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap