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

Python base.Config类代码示例

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

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



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

示例1: setUp

  def setUp(self):
    with temporary_file() as ini:
      ini.write(
'''
[DEFAULT]
answer: 42
scale: 1.2
path: /a/b/%(answer)s
embed: %(path)s::foo
disclaimer:
  Let it be known
  that.

[a]
fast: True
list: [1, 2, 3, %(answer)s]

[b]
preempt: False
dict: {
    'a': 1,
    'b': %(answer)s,
    'c': ['%(answer)s', %(answer)s]
  }
''')
      ini.close()
      self.config = Config.load(configpath=ini.name)
开发者ID:BabyDuncan,项目名称:commons,代码行数:27,代码来源:test_config.py


示例2: __init__

    def __init__(self, target, root_dir, extra_targets=None):
        self._config = Config.load()
        self._target = target
        self._root = root_dir
        self._cache = BuildCache(
            os.path.join(self._config.get("python-setup", "artifact_cache"), "%s" % PythonIdentity.get())
        )
        self._extra_targets = list(extra_targets) if extra_targets is not None else []
        self._extra_targets.append(self._get_common_python())

        cachedir = self._config.get("python-setup", "cache")
        safe_mkdir(cachedir)
        self._eggcache = cachedir

        local_repo = "file://%s" % os.path.realpath(cachedir)
        self._repos = [local_repo] + self._config.getlist("python-setup", "repos")
        self._fetcher = ReqFetcher(repos=self._repos, cache=cachedir)
        self._index = None
        for index in self._config.getlist("python-setup", "indices"):
            if PythonChroot.can_contact_index(index):
                self._index = index
                break
        self._additional_reqs = set()

        distdir = self._config.getdefault("pants_distdir")
        distpath = tempfile.mktemp(dir=distdir, prefix=target.name)
        self.env = PythonEnvironment(distpath)
开发者ID:satifanie,项目名称:commons,代码行数:27,代码来源:python_chroot.py


示例3: __init__

 def __init__(self, targets):
   self._config = Config.load()
   self._targets = targets
   self._resolver = SilentResolver(
     caches = self._config.getlist('python-setup', 'local_eggs') +
               [self._config.get('python-setup', 'install_cache')],
     install_cache = self._config.get('python-setup', 'install_cache'),
     fetcher = fetcher_from_config(self._config))
开发者ID:dynamicguy,项目名称:commons,代码行数:8,代码来源:resolver.py


示例4: _run

def _run():
  version = get_version()
  if len(sys.argv) == 2 and sys.argv[1] == _VERSION_OPTION:
    _do_exit(version)

  root_dir = get_buildroot()
  if not os.path.exists(root_dir):
    _exit_and_fail('PANTS_BUILD_ROOT does not point to a valid path: %s' % root_dir)

  if len(sys.argv) < 2 or (len(sys.argv) == 2 and sys.argv[1] in _HELP_ALIASES):
    _help(version, root_dir)

  command_class, command_args = _parse_command(root_dir, sys.argv[1:])

  parser = optparse.OptionParser(version=version)
  RcFile.install_disable_rc_option(parser)
  parser.add_option(_LOG_EXIT_OPTION,
                    action='store_true',
                    default=False,
                    dest='log_exit',
                    help = 'Log an exit message on success or failure.')

  config = Config.load()
  run_tracker = RunTracker(config)
  report = initial_reporting(config, run_tracker)
  run_tracker.start(report)

  url = run_tracker.run_info.get_info('report_url')
  if url:
    run_tracker.log(Report.INFO, 'See a report at: %s' % url)
  else:
    run_tracker.log(Report.INFO, '(To run a reporting server: ./pants server)')

  command = command_class(run_tracker, root_dir, parser, command_args)
  try:
    if command.serialized():
      def onwait(pid):
        print('Waiting on pants process %s to complete' % _process_info(pid), file=sys.stderr)
        return True
      runfile = os.path.join(root_dir, '.pants.run')
      lock = Lock.acquire(runfile, onwait=onwait)
    else:
      lock = Lock.unlocked()
    try:
      result = command.run(lock)
      _do_exit(result)
    except KeyboardInterrupt:
      command.cleanup()
      raise
    finally:
      lock.release()
  finally:
    run_tracker.end()
    # Must kill nailguns only after run_tracker.end() is called, because there may still
    # be pending background work that needs a nailgun.
    if (hasattr(command.options, 'cleanup_nailguns') and command.options.cleanup_nailguns) \
        or config.get('nailgun', 'autokill', default=False):
      NailgunTask.killall(None)
开发者ID:alfss,项目名称:commons,代码行数:58,代码来源:pants_exe.py


示例5: setup_parser

 def setup_parser(self, parser, args):
   parser.set_usage("\n"
                    "  %prog build (options) [spec] (build args)\n"
                    "  %prog build (options) [spec]... -- (build args)")
   parser.add_option("-t", "--timeout", dest="conn_timeout", type="int",
                     default=Config.load().getdefault('connection_timeout'),
                     help="Number of seconds to wait for http connections.")
   parser.disable_interspersed_args()
   parser.epilog = """Builds the specified Python target(s). Use ./pants goal for JVM and other targets."""
开发者ID:steliokontos,项目名称:commons,代码行数:9,代码来源:build.py


示例6: generate_coverage_config

def generate_coverage_config(target):
  cp = configparser.ConfigParser()
  cp.readfp(Compatibility.StringIO(DEFAULT_COVERAGE_CONFIG))
  cp.add_section('html')
  target_dir = os.path.join(Config.load().getdefault('pants_distdir'), 'coverage',
      os.path.dirname(target.address.buildfile.relpath), target.name)
  safe_mkdir(target_dir)
  cp.set('html', 'directory', target_dir)
  return cp
开发者ID:CodeWarltz,项目名称:commons,代码行数:9,代码来源:test_builder.py


示例7: setUp

  def setUp(self):
    with temporary_file() as ini:
      ini.write(
'''
[python-setup]
platforms: [
  'current',
  'linux-x86_64']
''')
      ini.close()
      self.config = Config.load(configpath=ini.name)
开发者ID:BabyDuncan,项目名称:commons,代码行数:11,代码来源:test_python_chroot.py


示例8: __init__

  def __init__(self, target, root_dir, extra_targets=None, builder=None, conn_timeout=None):
    self._config = Config.load()
    self._target = target
    self._root = root_dir
    self._key_generator = CacheKeyGenerator()
    self._extra_targets = list(extra_targets) if extra_targets is not None else []
    self._resolver = MultiResolver.from_target(self._config, target, conn_timeout=conn_timeout)
    self._builder = builder or PEXBuilder(tempfile.mkdtemp())

    # Note: unrelated to the general pants artifact cache.
    self._egg_cache_root = os.path.join(self._config.get('python-setup', 'artifact_cache'),
                                        '%s' % PythonIdentity.get())
开发者ID:dynamicguy,项目名称:commons,代码行数:12,代码来源:python_chroot.py


示例9: __init__

  def __init__(self, target, root_dir, extra_targets=None, builder=None, conn_timeout=None):
    self._config = Config.load()
    self._target = target
    self._root = root_dir
    self._key_generator = CacheKeyGenerator()
    self._extra_targets = list(extra_targets) if extra_targets is not None else []
    self._resolver = MultiResolver.from_target(self._config, target, conn_timeout=conn_timeout)
    self._builder = builder or PEXBuilder(tempfile.mkdtemp())

    artifact_cache_root = os.path.join(self._config.get('python-setup', 'artifact_cache'),
                                       '%s' % PythonIdentity.get())
    self._artifact_cache = FileBasedArtifactCache(None, self._root, artifact_cache_root,
                                                  self._builder.add_dependency_file)
开发者ID:BabyDuncan,项目名称:commons,代码行数:13,代码来源:python_chroot.py


示例10: setup_parser

 def setup_parser(self, parser, args):
   parser.set_usage("\n"
                    "  %prog py (options) [spec] args\n")
   parser.disable_interspersed_args()
   parser.add_option("-t", "--timeout", dest="conn_timeout", type="int",
                     default=Config.load().getdefault('connection_timeout'),
                     help="Number of seconds to wait for http connections.")
   parser.add_option("--pex", dest="pex", default=False, action='store_true',
                     help="dump a .pex of this chroot")
   parser.add_option("--resolve", dest="resolve", default=False, action='store_true',
                     help="resolve targets instead of building.")
   parser.add_option("-v", "--verbose", dest="verbose", default=False, action='store_true',
                     help="show verbose output.")
   parser.epilog = """Interact with the chroot of the specified target."""
开发者ID:steliokontos,项目名称:commons,代码行数:14,代码来源:py.py


示例11: setup_parser

 def setup_parser(self, parser, args):
   parser.set_usage("\n"
                    "  %prog build (options) [spec] (build args)\n"
                    "  %prog build (options) [spec]... -- (build args)")
   parser.add_option("-t", "--timeout", dest="conn_timeout", type="int",
                     default=Config.load().getdefault('connection_timeout'),
                     help="Number of seconds to wait for http connections.")
   parser.add_option('-i', '--interpreter', dest='interpreter', default=None,
                     help='The interpreter requirement for this chroot.')
   parser.add_option('-v', '--verbose', dest='verbose', default=False, action='store_true',
                     help='Show verbose output.')
   parser.disable_interspersed_args()
   parser.epilog = ('Builds the specified Python target(s). Use ./pants goal for JVM and other '
                    'targets.')
开发者ID:alfss,项目名称:commons,代码行数:14,代码来源:build.py


示例12: compiled_idl

  def compiled_idl(cls, idl_dep, generated_deps=None, compiler=None, language=None, namespace_map=None):
    """Marks a jar as containing IDL files that should be fetched and processed locally.

    idl_dep:        A dependency resolvable to a single jar library.
    generated_deps: Dependencies for the code that will be generated from "idl_dep"
    compiler:       The thrift compiler to apply to the fetched thrift IDL files.
    language:       The language to generate code for - supported by some compilers
    namespace_map:  A mapping from IDL declared namespaces to custom namespaces - supported by some
                    compilers.
    """
    deps = [t for t in idl_dep.resolve() if t.is_concrete]
    if not len(deps) == 1:
      raise TaskError('Can only arrange for compiled idl for a single dependency at a time, '
                      'given:\n\t%s' % '\n\t'.join(map(str, deps)))
    jar = deps.pop()
    if not isinstance(jar, JarDependency):
      raise TaskError('Can only arrange for compiled idl from a jar dependency, given: %s' % jar)

    request = (jar, compiler, language)
    namespace_signature = None
    if namespace_map:
      sha = hashlib.sha1()
      for ns_from, ns_to in sorted(namespace_map.items()):
        sha.update(ns_from)
        sha.update(ns_to)
      namespace_signature = sha.hexdigest()
    request += (namespace_signature,)

    if request not in cls._PLACEHOLDER_BY_REQUEST:
      if not cls._EXTRACT_BASE:
        config = Config.load()
        cls._EXTRACT_BASE = config.get('idl-extract', 'workdir')
        safe_mkdir(cls._EXTRACT_BASE)
        SourceRoot.register(cls._EXTRACT_BASE, JavaThriftLibrary)

      with ParseContext.temp(cls._EXTRACT_BASE):
        # TODO(John Sirois): abstract ivy specific configurations notion away
        jar._configurations.append('idl')
        jar.with_artifact(configuration='idl', classifier='idl')
        target_name = '-'.join(filter(None, (jar.id, compiler, language, namespace_signature)))
        placeholder = JavaThriftLibrary(target_name,
                                        sources=None,
                                        dependencies=[jar] + (generated_deps or []),
                                        compiler=compiler,
                                        language=language,
                                        namespace_map=namespace_map)
        cls._PLACEHOLDER_BY_REQUEST[request] = placeholder
        cls._PLACEHOLDERS_BY_JAR[jar].append(placeholder)
    return cls._PLACEHOLDER_BY_REQUEST[request]
开发者ID:alfss,项目名称:commons,代码行数:49,代码来源:extract.py


示例13: __init__

  def __init__(self, run_tracker, root_dir, parser, argv):
    Command.__init__(self, run_tracker, root_dir, parser, argv)

    if not self.args:
      self.error("A spec argument is required")

    self._config = Config.load()
    self._root = root_dir

    address = Address.parse(root_dir, self.args[0])
    self.target = Target.get(address)
    if self.target is None:
      self.error('%s is not a valid target!' % self.args[0])

    if not self.target.provides:
      self.error('Target must provide an artifact.')
开发者ID:CodeWarltz,项目名称:commons,代码行数:16,代码来源:setup_py.py


示例14: profile_classpath

def profile_classpath(profile, java_runner=None, config=None, ivy_jar=None, ivy_settings=None, workunit_factory=None):
    # TODO(John Sirois): consider rework when ant backend is gone and there is no more need to share
    # path structure

    java_runner = java_runner or runjava_indivisible

    config = config or Config.load()

    profile_dir = config.get("ivy-profiles", "workdir")
    profile_libdir = os.path.join(profile_dir, "%s.libs" % profile)
    profile_check = "%s.checked" % profile_libdir
    if not os.path.exists(profile_check):
        # TODO(John Sirois): refactor IvyResolve to share ivy invocation command line bits
        ivy_classpath = [ivy_jar] if ivy_jar else config.getlist("ivy", "classpath")

        safe_mkdir(profile_libdir)
        ivy_settings = ivy_settings or config.get("ivy", "ivy_settings")
        ivy_xml = os.path.join(profile_dir, "%s.ivy.xml" % profile)
        ivy_opts = [
            "-settings",
            ivy_settings,
            "-ivy",
            ivy_xml,
            # TODO(John Sirois): this pattern omits an [organisation]- prefix to satisfy IDEA jar naming
            # needs for scala - isolate this hack to idea.py where it belongs
            "-retrieve",
            "%s/[artifact]-[revision](-[classifier]).[ext]" % profile_libdir,
            "-sync",
            "-symlink",
            "-types",
            "jar",
            "bundle",
            "-confs",
            "default",
        ]
        result = java_runner(
            classpath=ivy_classpath,
            main="org.apache.ivy.Main",
            workunit_factory=workunit_factory,
            workunit_name="%s:bootstrap" % profile,
            opts=ivy_opts,
        )
        if result != 0:
            raise TaskError("Failed to load profile %s, ivy exit code %s" % (profile, str(result)))
        touch(profile_check)

    return [os.path.join(profile_libdir, jar) for jar in os.listdir(profile_libdir)]
开发者ID:dynamicguy,项目名称:commons,代码行数:47,代码来源:binary_util.py


示例15: __init__

  def __init__(self, target, root_dir, extra_targets=None, builder=None):
    self._config = Config.load()

    self._target = target
    self._root = root_dir
    self._cache = BuildCache(os.path.join(self._config.get('python-setup', 'artifact_cache'),
      '%s' % PythonIdentity.get()))
    self._extra_targets = list(extra_targets) if extra_targets is not None else []
    self._resolver = PythonResolver([self._target] + self._extra_targets)
    self._builder = builder or PEXBuilder(tempfile.mkdtemp())
    self._platforms = (Platform.current(),)
    self._pythons = (sys.version[:3],)

    # TODO(wickman) Should this be in the binary builder?
    if isinstance(self._target, PythonBinary):
      self._platforms = self._target._platforms
      self._pythons = self._target._interpreters
开发者ID:avadh,项目名称:commons,代码行数:17,代码来源:python_chroot.py


示例16: iter_generated_sources

  def iter_generated_sources(cls, target, root, config=None):
    config = config or Config.load()
    # This is sort of facepalmy -- python.new will make this much better.
    for target_type, target_builder in cls.GENERATED_TARGETS.items():
      if isinstance(target, target_type):
        builder_cls = target_builder
        break
    else:
      raise TypeError(
          'write_generated_sources could not find suitable code generator for %s' % type(target))

    builder = builder_cls(target, root, config)
    builder.generate()
    for root, _, files in os.walk(builder.package_root):
      for fn in files:
        target_file = os.path.join(root, fn)
        yield os.path.relpath(target_file, builder.package_root), target_file
开发者ID:CodeWarltz,项目名称:commons,代码行数:17,代码来源:setup_py.py


示例17: __init__

  def __init__(self, run_tracker, root_dir, parser, argv):
    Command.__init__(self, run_tracker, root_dir, parser, argv)

    if not self.args:
      self.error("A spec argument is required")

    self.config = Config.load()
    self.interpreter_cache = PythonInterpreterCache(self.config, logger=self.debug)
    self.interpreter_cache.setup()
    interpreters = self.interpreter_cache.select_interpreter(
        list(self.interpreter_cache.matches([self.options.interpreter]
            if self.options.interpreter else [''])))
    if len(interpreters) != 1:
      self.error('Unable to detect suitable interpreter.')
    else:
      self.debug('Selected %s' % interpreters[0])
    self.interpreter = interpreters[0]

    try:
      specs_end = self.args.index('--')
      if len(self.args) > specs_end:
        self.build_args = self.args[specs_end+1:len(self.args)+1]
      else:
        self.build_args = []
    except ValueError:
      specs_end = 1
      self.build_args = self.args[1:] if len(self.args) > 1 else []

    self.targets = OrderedSet()
    for spec in self.args[0:specs_end]:
      try:
        address = Address.parse(root_dir, spec)
      except:
        self.error("Problem parsing spec %s: %s" % (spec, traceback.format_exc()))

      try:
        target = Target.get(address)
      except:
        self.error("Problem parsing BUILD target %s: %s" % (address, traceback.format_exc()))

      if not target:
        self.error("Target %s does not exist" % address)
      self.targets.update(tgt for tgt in target.resolve() if tgt.is_concrete)
开发者ID:alfss,项目名称:commons,代码行数:43,代码来源:build.py


示例18: execute

  def execute(self):
    config = Config.load()
    distdir = config.getdefault('pants_distdir')
    setup_dir = os.path.join(distdir, '%s-%s' % (
        self.target.provides._name, self.target.provides._version))
    chroot = Chroot(distdir, name=self.target.provides._name)
    self.write_sources(chroot)
    self.write_setup(chroot)
    if os.path.exists(setup_dir):
      import shutil
      shutil.rmtree(setup_dir)
    os.rename(chroot.path(), setup_dir)

    with pushd(setup_dir):
      cmd = '%s setup.py %s' % (sys.executable, self.options.run or 'sdist')
      print('Running "%s" in %s' % (cmd, setup_dir))
      extra_args = {} if self.options.run else dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      po = subprocess.Popen(cmd, shell=True, **extra_args)
      po.wait()

    if self.options.run:
      print('Ran %s' % cmd)
      print('Output in %s' % setup_dir)
      return po.returncode
    elif po.returncode != 0:
      print('Failed to run %s!' % cmd)
      for line in po.stdout.read().splitlines():
        print('stdout: %s' % line)
      for line in po.stderr.read().splitlines():
        print('stderr: %s' % line)
      return po.returncode

    expected_tgz = '%s-%s.tar.gz' % (self.target.provides._name, self.target.provides._version)
    expected_target = os.path.join(setup_dir, 'dist', expected_tgz)
    dist_tgz = os.path.join(distdir, expected_tgz)
    if not os.path.exists(expected_target):
      print('Could not find expected target %s!' % expected_target)
      sys.exit(1)
    safe_delete(dist_tgz)
    os.rename(expected_target, dist_tgz)
    print('Wrote %s' % dist_tgz)
    safe_rmtree(setup_dir)
开发者ID:steliokontos,项目名称:commons,代码行数:42,代码来源:setup_py.py


示例19: safe_args

def safe_args(args,
              max_args=None,
              config=None,
              argfile=None,
              delimiter='\n',
              quoter=None,
              delete=True):
  """
    Yields args if there are less than a limit otherwise writes args to an argfile and yields an
    argument list with one argument formed from the path of the argfile.

    :args The args to work with.
    :max_args The maximum number of args to let though without writing an argfile.  If not specified
              then the maximum will be loaded from config.
    :config Used to lookup the configured maximum number of args that can be passed to a subprocess;
            defaults to the default config and looks for key 'max_subprocess_args' in the DEFAULTS.
    :argfile The file to write args to when there are too many; defaults to a temporary file.
    :delimiter The delimiter to insert between args written to the argfile, defaults to '\n'
    :quoter A function that can take the argfile path and return a single argument value;
            defaults to:
            <code>lambda f: '@' + f<code>
    :delete If True deletes any arg files created upon exit from this context; defaults to True.
  """
  max_args = max_args or (config or Config.load()).getdefault('max_subprocess_args', int, 10)
  if len(args) > max_args:
    def create_argfile(fp):
      fp.write(delimiter.join(args))
      fp.close()
      return [quoter(fp.name) if quoter else '@%s' % fp.name]

    if argfile:
      try:
        with safe_open(argfile, 'w') as fp:
          yield create_argfile(fp)
      finally:
        if delete and os.path.exists(argfile):
          os.unlink(argfile)
    else:
      with temporary_file(cleanup=delete) as fp:
        yield create_argfile(fp)
  else:
    yield args
开发者ID:teddziuba,项目名称:commons,代码行数:42,代码来源:binary_util.py


示例20: setup_parser

 def setup_parser(self, parser, args):
   parser.set_usage('\n'
                    '  %prog py (options) [spec] args\n')
   parser.disable_interspersed_args()
   parser.add_option('-t', '--timeout', dest='conn_timeout', type='int',
                     default=Config.load().getdefault('connection_timeout'),
                     help='Number of seconds to wait for http connections.')
   parser.add_option('--pex', dest='pex', default=False, action='store_true',
                     help='Dump a .pex of this chroot instead of attempting to execute it.')
   parser.add_option('--ipython', dest='ipython', default=False, action='store_true',
                     help='Run the target environment in an IPython interpreter.')
   parser.add_option('-r', '--req', dest='extra_requirements', default=[], action='append',
                     help='Additional Python requirements to add to this chroot.')
   parser.add_option('-i', '--interpreter', dest='interpreter', default=None,
                     help='The interpreter requirement for this chroot.')
   parser.add_option('-e', '--entry_point', dest='entry_point', default=None,
                     help='The entry point for the generated PEX.')
   parser.add_option('-v', '--verbose', dest='verbose', default=False, action='store_true',
                     help='Show verbose output.')
   parser.epilog = """Interact with the chroot of the specified target."""
开发者ID:alfss,项目名称:commons,代码行数:20,代码来源:py.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python base.ParseContext类代码示例发布时间:2022-05-27
下一篇:
Python base.BuildFile类代码示例发布时间: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