python类Path()的实例源码

deploy.py 文件源码 项目:zipline-chinese 作者: zhanghan1990 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def main():
    print("Moving to %s." % HERE)
    with path(HERE):
        print("Building docs with 'make html'")
        check_call(['make', 'html'])

        print("Clearing temp location '%s'" % TEMP_LOCATION)
        rmtree(TEMP_LOCATION, ignore_errors=True)

        with removing(TEMP_LOCATION):
            print("Copying built files to temp location.")
            move('build/html', TEMP_LOCATION)

            print("Moving to '%s'" % ZIPLINE_ROOT)
            os.chdir(ZIPLINE_ROOT)

            print("Checking out gh-pages branch.")
            check_call(
                [
                    'git', 'branch', '-f',
                    '--track', 'gh-pages', 'origin/gh-pages'
                ]
            )
            check_call(['git', 'checkout', 'gh-pages'])
            check_call(['git', 'reset', '--hard', 'origin/gh-pages'])

            print("Copying built files:")
            for file_ in glob(TEMP_LOCATION_GLOB):
                base = basename(file_)

                print("%s -> %s" % (file_, base))
                ensure_not_exists(base)
                move(file_, '.')

    print()
    print("Updated documentation branch in directory %s" % ZIPLINE_ROOT)
    print("If you are happy with these changes, commit and push to gh-pages.")
db.py 文件源码 项目:bigfootbot 作者: bigfoot547 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get(self, section, name, value):
        # Where are we going to store the database file.
        path_obj = path.path()
        path_obj.fromstr(self.database_dir)
        path_obj.add(section)
        path_obj.add(name)
        # The database file itself.
        entry = path.path()
        entry.fromstr(path_obj.tostr())
        entry.add("data")

        # Return the data.
        with open(entry.tostr(), 'r') as file:
            return file.read()
python.py 文件源码 项目:StatisKit 作者: StatisKit 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def generate(env, **kwargs):
    """Add Builders and construction variables to the Environment."""

    if not 'python' in env['TOOLS'][:-1]:

      env.Tool('system')

      PYTHON_VERSION = sysconfig.get_python_version()
      SYSTEM = env['SYSTEM']
      if SYSTEM == 'win':
          env.AppendUnique(LIBS = ['python' + PYTHON_VERSION.replace('.', '')],
                           CPPPATH = ['$PREFIX\..\include'])
      elif PYTHON_VERSION == '2.7':
              env.AppendUnique(CPPPATH = ['$PREFIX/include/python' + PYTHON_VERSION],
                               LIBS = ['python' + PYTHON_VERSION])
      elif PYTHON_VERSION == '3.6':
              env.AppendUnique(CPPPATH = ['$PREFIX/include/python' + PYTHON_VERSION + 'm'],
                               LIBS = ['python' + PYTHON_VERSION + 'm'])
      else:
          raise NotImplementedError('Python ' + PYTHON_VERSION)

      if SYSTEM == 'win':
        env['SP_DIR'] = '$PREFIX\..\Lib\site-packages'
      else:
        env['SP_DIR'] = '$PREFIX/lib/python' + PYTHON_VERSION + '/site-packages'

      def PythonPackage(env, **kwargs):
        pattern = kwargs.pop('pattern', None)
        packages = {kwarg : Path(env.Dir(kwargs[kwarg]).srcnode().abspath).walkfiles(pattern=pattern) for kwarg in kwargs}
        targets = []
        SP_DIR = env['SP_DIR']
        for package in packages:
            for source in packages[package]:
                if not source.ext in ['.lib', '.exp', '.so', '.dll']:
                    directory = os.path.join(SP_DIR, *package.split('.'))
                    directory = os.path.join(directory, source.relpath(env.Dir(kwargs[package]).srcnode().abspath).parent)
                    targets.append(env.Install(directory, source.abspath()))
        return targets

      env.AddMethod(PythonPackage)
util.py 文件源码 项目:sphinxcontrib-websupport 作者: sphinx-doc 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def assert_node(node, cls=None, xpath="", **kwargs):
    if cls:
        if isinstance(cls, list):
            assert_node(node, cls[0], xpath=xpath, **kwargs)
            if cls[1:]:
                if isinstance(cls[1], tuple):
                    assert_node(node, cls[1], xpath=xpath, **kwargs)
                else:
                    assert len(node) == 1, \
                        'The node%s has %d child nodes, not one' % (xpath, len(node))
                    assert_node(node[0], cls[1:], xpath=xpath + "[0]", **kwargs)
        elif isinstance(cls, tuple):
            assert len(node) == len(cls), \
                'The node%s has %d child nodes, not %r' % (xpath, len(node), len(cls))
            for i, nodecls in enumerate(cls):
                path = xpath + "[%d]" % i
                assert_node(node[i], nodecls, xpath=path, **kwargs)
        elif isinstance(cls, string_types):
            assert node == cls, 'The node %r is not %r: %r' % (xpath, cls, node)
        else:
            assert isinstance(node, cls), \
                'The node%s is not subclass of %r: %r' % (xpath, cls, node)

    for key, value in kwargs.items():
        assert key in node, 'The node%s does not have %r attribute: %r' % (xpath, key, node)
        assert node[key] == value, \
            'The node%s[%s] is not %r: %r' % (xpath, key, value, node[key])
util.py 文件源码 项目:sphinxcontrib-websupport 作者: sphinx-doc 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def etree_parse(path):
    with warnings.catch_warnings(record=False):
        warnings.filterwarnings("ignore", category=DeprecationWarning)
        return ElementTree.parse(path)
util.py 文件源码 项目:sphinxcontrib-websupport 作者: sphinx-doc 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def cleanup(self, doctrees=False):
        AutoDirective._registry.clear()
        ModuleAnalyzer.cache.clear()
        LaTeXBuilder.usepackages = []
        sys.path[:] = self._saved_path
        sys.modules.pop('autodoc_fodder', None)
        directives._directives = self._saved_directives
        roles._roles = self._saved_roles
        for method in dir(nodes.GenericNodeVisitor):
            if method.startswith('visit_') and \
               method not in self._saved_nodeclasses:
                delattr(nodes.GenericNodeVisitor, 'visit_' + method[6:])
                delattr(nodes.GenericNodeVisitor, 'depart_' + method[6:])
util.py 文件源码 项目:sphinxcontrib-websupport 作者: sphinx-doc 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def find_files(root, suffix=None):
    for dirpath, dirs, files in os.walk(root, followlinks=True):
        dirpath = path(dirpath)
        for f in [f for f in files if not suffix or f.endswith(suffix)]:
            fpath = dirpath / f
            yield os.path.relpath(fpath, root)
commands.py 文件源码 项目:docl 作者: cloudify-cosmo 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def pull_image(no_progress=False):
    # try contacting the docker daemon first, to break early if it's not
    # reachable - before the long download
    quiet_docker.version()

    online_sha1 = requests.get(
        configuration.manager_image_commit_sha_url).text.strip()
    local_sha1 = work.last_pulled_image_commit_sha1
    if online_sha1 == local_sha1:
        logger.info('Current image is the latest image. It is based on the '
                    'following commit in the manager blueprints repo: {}'
                    .format(local_sha1))
        return
    logger.info('Download manager image from {} to {}'
                .format(configuration.manager_image_url,
                        work.pulled_image_path))
    if os.path.exists(work.pulled_image_path):
        os.remove(work.pulled_image_path)
    files.download(url=configuration.manager_image_url,
                   output_path=work.pulled_image_path,
                   no_progress=no_progress)
    logger.info('Loading image into docker (may take a while)')
    quiet_docker.load(gzip('-dc', work.pulled_image_path,
                           _piped=True,
                           _out_bufsize=constants.BUFFER_SIZE),
                      _in_bufsize=constants.BUFFER_SIZE)
    work.last_pulled_image_commit_sha1 = online_sha1
commands.py 文件源码 项目:docl 作者: cloudify-cosmo 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def build_agent(container_id=None):
    logger.info('Rebuilding agent package')
    container_id = container_id or work.last_container_id
    quiet_docker('exec', container_id, 'tar', 'czf',
                 configuration.agent_package_path, '-C',
                 path(constants.AGENT_TEMPLATE_DIR).dirname(),
                 path(constants.AGENT_TEMPLATE_DIR).basename())
commands.py 文件源码 项目:docl 作者: cloudify-cosmo 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _write_config(container_ip, config_path):
    path(config_path).write_text(yaml.safe_dump({
        'manager': {
            'public_ip': container_ip,
            'private_ip': container_ip,
            'set_manager_ip_on_boot': True,
            'security': {
                'admin_password': 'admin'
            }
        }
    }))
commands.py 文件源码 项目:docl 作者: cloudify-cosmo 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _write_container_details(container_id, container_ip, details_path):
    path(details_path).write_text(yaml.safe_dump({
        'id': container_id,
        'ip': container_ip,
    }))
configuration.py 文件源码 项目:docl 作者: cloudify-cosmo 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def save(self,
             docker_host,
             ssh_key_path,
             clean_image_docker_tag,
             manager_image_docker_tag,
             source_root,
             workdir,
             reset,
             debug_ip):
        if not self.conf_dir.exists():
            self.conf_dir.mkdir()
        conf = self.conf_dir / 'config.yaml'
        if conf.exists() and not reset:
            raise argh.CommandError('Already initialized. '
                                    'Run "docl init --reset"')
        workdir = workdir or self.conf_dir / 'work'
        workdir = path(workdir).expanduser().abspath()
        conf.write_text(yaml.safe_dump({
            'ssh_key_path': str(ssh_key_path),
            'docker_host': docker_host,
            'clean_image_docker_tag': clean_image_docker_tag,
            'manager_image_docker_tag': manager_image_docker_tag,
            'source_root': source_root,
            'workdir': str(workdir),
            'services': constants.SERVICES,
            'expose': constants.EXPOSE,
            'publish': constants.PUBLISH,
            'container_hostname': constants.HOSTNAME,
            'package_dir': constants.PACKAGE_DIR,
            'package_services': constants.PACKAGE_SERVICES,
            'env_packages': constants.ENV_PACKAGES,
            'resources': constants.RESOURCES,
            'agent_package_path': constants.AGENT_PACKAGE_PATH,
            'manager_image_url': constants.MANAGER_IMAGE_URL,
            'manager_image_commit_sha_url':
                constants.MANAGER_IMAGE_COMMIT_SHA_URL,
            'debug_ip': debug_ip
        }, default_flow_style=False))
configuration.py 文件源码 项目:docl 作者: cloudify-cosmo 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def conf_dir(self):
        return path(os.environ.get(constants.DOCL_HOME_ENV_VAR,
                                   '~/.docl')).expanduser()
configuration.py 文件源码 项目:docl 作者: cloudify-cosmo 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def ssh_key_path(self):
        return path(self.conf.get('ssh_key_path'))
configuration.py 文件源码 项目:docl 作者: cloudify-cosmo 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def workdir(self):
        return path(self.conf['workdir'])
hierarchy_layout.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def add_layout_pin_center_rect(self, text, layer, offset, width=None, height=None):
        """ Creates a path like pin with center-line convention """
        if width==None:
            width=drc["minwidth_{0}".format(layer)]
        if height==None:
            height=drc["minwidth_{0}".format(layer)]

        ll_offset = offset - vector(0.5*width,0.5*height)

        return self.add_layout_pin(text, layer, ll_offset, width, height)
hierarchy_layout.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def add_path(self, layer, coordinates, width=None):
        """Connects a routing path on given layer,coordinates,width."""
        debug.info(4,"add path " + str(layer) + " " + str(coordinates))
        import path
        # NOTE: (UNTESTED) add_path(...) is currently not used
        # negative layers indicate "unused" layers in a given technology
        #layerNumber = techlayer[layer]
        #if layerNumber >= 0:
        #    self.objs.append(geometry.path(layerNumber, coordinates, width))

        path.path(obj=self,
                  layer=layer, 
                  position_list=coordinates, 
                  width=drc["minwidth_{}".format(layer)])
hierarchy_layout.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def add_route(self, design, layers, coordinates):
        """Connects a routing path on given layer,coordinates,width. The
        layers are the (horizontal, via, vertical). add_wire assumes
        preferred direction routing whereas this includes layers in
        the coordinates.
        """
        import route
        debug.info(4,"add route " + str(layers) + " " + str(coordinates))
        # add an instance of our path that breaks down into rectangles and contacts
        route.route(obj=self,
                    layer_stack=layers, 
                    path=coordinates)
hierarchy_layout.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def add_wire(self, layers, coordinates):
        """Connects a routing path on given layer,coordinates,width.
        The layers are the (horizontal, via, vertical). """
        import wire
        # add an instance of our path that breaks down into rectangles and contacts
        wire.wire(obj=self,
                  layer_stack=layers, 
                  position_list=coordinates)
normpath.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def invalid1(self):
        raise NormpathException("invalid result (the requested value is undefined due to path properties)")
normpath.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def pathitem(self):
        return path.lineto_pt(self.x1_pt, self.y1_pt)
normpath.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def bbox(self):
        xmin_pt, xmax_pt = path._bezierpolyrange(self.x0_pt, self.x1_pt, self.x2_pt, self.x3_pt)
        ymin_pt, ymax_pt = path._bezierpolyrange(self.y0_pt, self.y1_pt, self.y2_pt, self.y3_pt)
        return bboxmodule.bbox_pt(xmin_pt, ymin_pt, xmax_pt, ymax_pt)
normpath.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def pathitem(self):
        return path.curveto_pt(self.x1_pt, self.y1_pt, self.x2_pt, self.y2_pt, self.x3_pt, self.y3_pt)
normpath.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def extend(self, normsubpathitems):
        """extend path by normsubpathitems

        Fails on closed normsubpath.
        """
        for normsubpathitem in normsubpathitems:
            self.append(normsubpathitem)
normpath.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def transformed(self, trafo):
        """return transformed path"""
        nnormsubpath = normsubpath(epsilon=self.epsilon)
        for pitem in self.normsubpathitems:
            nnormsubpath.append(pitem.transformed(trafo))
        if self.closed:
            nnormsubpath.close()
        elif self.skippedline is not None:
            nnormsubpath.append(self.skippedline.transformed(trafo))
        return nnormsubpath
normpath.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _distributeparams(self, params):
        """return a dictionary mapping subpathindices to a tuple of a paramindices and subpathparams

        subpathindex specifies a subpath containing one or several positions.
        paramindex specify the index of the normpathparam in the original list and
        subpathparam is the parameter value in the subpath.
        """

        result = {}
        for i, param in enumerate(params):
            assert param.normpath is self, "normpathparam has to belong to this path"
            result.setdefault(param.normsubpathindex, ([], []))
            result[param.normsubpathindex][0].append(i)
            result[param.normsubpathindex][1].append(param.normsubpathparam)
        return result
normpath.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def append(self, item):
        """append a normpath by a normsubpath or a pathitem"""
        if isinstance(item, normsubpath):
            # the normsubpaths list can be appended by a normsubpath only
            self.normsubpaths.append(item)
        elif isinstance(item, path.pathitem):
            # ... but we are kind and allow for regular path items as well
            # in order to make a normpath to behave more like a regular path
            if self.normsubpaths:
                context = path.context(*(self.normsubpaths[-1].atend_pt() +
                                         self.normsubpaths[-1].atbegin_pt()))
                item.updatenormpath(self, context)
            else:
                self.normsubpaths = item.createnormpath(self).normsubpaths
normpath.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def atbegin_pt(self):
        """return coordinates of the beginning of first subpath in normpath in pts"""
        if self.normsubpaths:
            return self.normsubpaths[0].atbegin_pt()
        else:
            raise NormpathException("cannot return first point of empty path")
normpath.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def atend_pt(self):
        """return coordinates of the end of last subpath in normpath in pts"""
        if self.normsubpaths:
            return self.normsubpaths[-1].atend_pt()
        else:
            raise NormpathException("cannot return last point of empty path")
normpath.py 文件源码 项目:OpenRAM 作者: mguthaus 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def end(self):
        """return param corresponding of the end of the path"""
        if self.normsubpaths:
            return normpathparam(self, len(self)-1, len(self.normsubpaths[-1]))
        else:
            raise NormpathException("empty path")


问题


面经


文章

微信
公众号

扫码关注公众号