我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用path.path()。
def add(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") # Make the directoies. os.makedirs(path_obj.tostr(), exist_ok = True) # And write the value. with open(entry.tostr(), 'w') as file: file.write(value)
def init(docker_host=constants.DOCKER_HOST, ssh_key_path=constants.SSH_KEY, clean_image_docker_tag=constants.CLEAN_IMAGE_DOCKER_TAG, manager_image_docker_tag=constants.MANAGER_IMAGE_DOCKER_TAG, source_root=constants.SOURCE_ROOT, workdir=None, reset=False, debug_ip=None): ssh_key_path = path(ssh_key_path).expanduser() if not ssh_key_path.isfile(): raise argh.CommandError( 'You need to create a key (see man ssh-keygen) first' ) configuration.save( docker_host=docker_host, ssh_key_path=ssh_key_path.abspath(), clean_image_docker_tag=clean_image_docker_tag, manager_image_docker_tag=manager_image_docker_tag, source_root=source_root, workdir=workdir, reset=reset, debug_ip=debug_ip) logger.info('Configuration is saved to {}. Feel free to change it to your ' 'liking.'.format(configuration.conf_path)) work.init()
def _build_volumes(): # resources should be able to override env packages which is why # we use a dist based in the destination directory volumes = {} for env, packages in configuration.env_packages.items(): for package in packages: src = '{}/{}/{}'.format(configuration.source_root, configuration.package_dir[package], package) dst = '/opt/{}/env/lib/python2.7/site-packages/{}'.format(env, package) volumes[dst] = '{}:{}:ro'.format(src, dst) for resource in configuration.resources: dst = resource['dst'] if resource.get('write'): permissions = 'rw' else: permissions = 'ro' src = resource['src'] if not path(src).isabs(): src = '{}/{}'.format(configuration.source_root, src) volumes[dst] = '{}:{}:{}'.format(src, dst, permissions) return volumes.values()
def add_layout_pin_center_segment(self, text, layer, start, end): """ Creates a path like pin with center-line convention """ debug.check(start.x==end.x or start.y==end.y,"Cannot have a non-manhatten layout pin.") minwidth_layer = drc["minwidth_{}".format(layer)] # one of these will be zero width = max(start.x,end.x) - min(start.x,end.x) height = max(start.y,end.y) - min(start.y,end.y) ll_offset = vector(min(start.x,end.x),min(start.y,end.y)) # Shift it down 1/2 a width in the 0 dimension if height==0: ll_offset -= vector(0,0.5*minwidth_layer) if width==0: ll_offset -= vector(0.5*minwidth_layer,0) # This makes sure it is long enough, but also it is not 0 width! height = max(minwidth_layer,height) width = max(minwidth_layer,width) return self.add_layout_pin(text, layer, ll_offset, width, height)
def intersect(self, other): """intersect self with other path Returns a tuple of lists consisting of the parameter values of the intersection points of the corresponding normpath. """ other = other.normpath() # here we build up the result intersections = ([], []) # Intersect all normsubpaths of self with the normsubpaths of # other. for ia, normsubpath_a in enumerate(self.normsubpaths): for ib, normsubpath_b in enumerate(other.normsubpaths): for intersection in zip(*normsubpath_a.intersect(normsubpath_b)): intersections[0].append(normpathparam(self, ia, intersection[0])) intersections[1].append(normpathparam(other, ib, intersection[1])) return intersections
def _tangent(self, params, length_pt): """return tangent vector of path at params If length_pt in pts is not None, the tangent vector will be scaled to the desired length. """ result = [None] * len(params) tangenttemplate = path.line_pt(0, 0, length_pt, 0).normpath() for normsubpathindex, (indices, params) in self._distributeparams(params).items(): for index, atrafo in zip(indices, self.normsubpaths[normsubpathindex].trafo(params)): if atrafo is invalid: result[index] = invalid else: result[index] = tangenttemplate.transformed(atrafo) return result
def create_vias(self): """ Add a via and corner square at every corner of the path.""" self.c=contact(self.layer_stack, (1, 1)) c_width = self.c.width c_height = self.c.height from itertools import tee,islice nwise = lambda g,n=2: zip(*(islice(g,i,None) for i,g in enumerate(tee(g,n)))) threewise=nwise(self.position_list,3) for (a, offset, c) in list(threewise): # add a exceptions to prevent a via when we don't change directions if a[0] == c[0]: continue if a[1] == c[1]: continue via_offset = [offset[0] + 0.5*c_height, offset[1] - 0.5*c_width] self.obj.add_via(layers=self.layer_stack, offset=via_offset, rotate=90) corner_offset = [offset[0] - 0.5*(c_height + self.vert_layer_width), offset[1] + 0.5*(c_width - self.horiz_layer_width)]
def standard_split(cls, root): """ Use standard train/dev/test/other splits 2-21/22/23/24, respectively. """ train = []; dev = []; test = []; other = [] for d in path(root).listdir(): if d.isdir(): number = int(d.basename()) # for some reason we drop sections < 2. if 2 <= number <= 21: train.append(d) elif number == 22: dev.append(d) elif number == 23: test.append(d) elif number == 24: other.append(d) train.sort() assert len(train) == 20 and len(test) == 1 and len(dev) == 1 return cls(train, dev, test, other)
def removing(path): try: yield finally: rmtree(path)
def ensure_not_exists(path): if not exists(path): return if isfile(path): os.unlink(path) else: rmtree(path)
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.")
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()
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)
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])
def etree_parse(path): with warnings.catch_warnings(record=False): warnings.filterwarnings("ignore", category=DeprecationWarning) return ElementTree.parse(path)
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:])
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)
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
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())
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' } } }))
def _write_container_details(container_id, container_ip, details_path): path(details_path).write_text(yaml.safe_dump({ 'id': container_id, 'ip': container_ip, }))
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))
def conf_dir(self): return path(os.environ.get(constants.DOCL_HOME_ENV_VAR, '~/.docl')).expanduser()
def ssh_key_path(self): return path(self.conf.get('ssh_key_path'))
def workdir(self): return path(self.conf['workdir'])
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)
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)])
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)
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)
def invalid1(self): raise NormpathException("invalid result (the requested value is undefined due to path properties)")
def pathitem(self): return path.lineto_pt(self.x1_pt, self.y1_pt)
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)
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)
def extend(self, normsubpathitems): """extend path by normsubpathitems Fails on closed normsubpath. """ for normsubpathitem in normsubpathitems: self.append(normsubpathitem)
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
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
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
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")
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")
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")
def extend(self, normsubpaths): """extend path by normsubpaths or pathitems""" for anormsubpath in normsubpaths: # use append to properly handle regular path items as well as normsubpaths self.append(anormsubpath)
def join(self, other): """join other normsubpath inplace Both normpaths must contain at least one normsubpath. The last normsubpath of self will be joined to the first normsubpath of other. """ other = other.normpath() if not self.normsubpaths: raise NormpathException("cannot join to empty path") if not other.normsubpaths: raise PathException("cannot join empty path") self.normsubpaths[-1].join(other.normsubpaths[0]) self.normsubpaths.extend(other.normsubpaths[1:])
def path(self): """return path corresponding to normpath""" pathitems = [] for normsubpath in self.normsubpaths: pathitems.extend(normsubpath.pathitems()) return path.path(*pathitems)
def split_pt(self, params): """split path at param(s) or arc length(s) in pts and return list of normpaths""" try: for param in params: break except: params = [params] return self._split_pt(self._convertparams(params, self.arclentoparam_pt))
def split(self, params): """split path at param(s) or arc length(s) and return list of normpaths""" try: for param in params: break except: params = [params] return self._split_pt(self._convertparams(params, self.arclentoparam))
def tangent_pt(self, params, length_pt): """return tangent vector of path at param(s) or arc length(s) in pts If length in pts is not None, the tangent vector will be scaled to the desired length. """ return self._tangent(self._convertparams(params, self.arclentoparam_pt), length_pt)
def omitends(self, box1, box2): """intersects a path with the boxes' paths""" # cut off the start of self # XXX how can decoration of this box1.path() be handled? sp = self.intersect(box1.path())[0] if sp: self.normsubpaths = self.split(sp[-1:])[1].normsubpaths # cut off the end of self sp = self.intersect(box2.path())[0] if sp: self.normsubpaths = self.split(sp[:1])[0].normsubpaths
def shortenpath(self, dists): """shortens a path by the given distances""" # XXX later, this should be done by extended boxes instead of intersecting with circles # cut off the start of self center = self.atbegin_pt() cutpath = path.circle_pt(center[0], center[1], dists[0]) try: cutpath = cutpath.normpath() except normpath.NormpathException: pass else: sp = self.intersect(cutpath)[0] self.normsubpaths = self.split(sp[-1:])[1].normsubpaths # cut off the end of self center = self.atend_pt() cutpath = path.circle_pt(center[0], center[1], dists[1]) try: cutpath = cutpath.normpath() except normpath.NormpathException: pass else: sp = self.intersect(cutpath)[0] if sp: self.normsubpaths = self.split(sp[:1])[0].normsubpaths ################ ## classes ################
def __init__(self, box1, box2, boxdists=[0,0]): self.box1 = box1 self.box2 = box2 connector_pt.__init__(self, [path.normsubpath([path.normline_pt(self.box1.center[0], self.box1.center[1], self.box2.center[0], self.box2.center[1])], closed=0)]) self.omitends(box1, box2) self.shortenpath(boxdists)
def normpath_selfintersections(self, np, epsilon): # <<< """return all self-intersection points of normpath np. This does not include the intersections of a single normcurve with itself, but all intersections of one normpathitem with a different one in the path""" n = len(np) linearparams = [] parampairs = [] paramsriap = {} for nsp_i in range(n): for nsp_j in range(nsp_i, n): for nspitem_i in range(len(np[nsp_i])): if nsp_j == nsp_i: nspitem_j_range = range(nspitem_i+1, len(np[nsp_j])) else: nspitem_j_range = range(len(np[nsp_j])) for nspitem_j in nspitem_j_range: intsparams = np[nsp_i][nspitem_i].intersect(np[nsp_j][nspitem_j], epsilon) if intsparams: for intsparam_i, intsparam_j in intsparams: if ( (abs(intsparam_i) < epsilon and abs(1-intsparam_j) < epsilon) or (abs(intsparam_j) < epsilon and abs(1-intsparam_i) < epsilon) ): continue npp_i = normpath.normpathparam(np, nsp_i, float(nspitem_i)+intsparam_i) npp_j = normpath.normpathparam(np, nsp_j, float(nspitem_j)+intsparam_j) linearparams.append(npp_i) linearparams.append(npp_j) paramsriap[id(npp_i)] = len(parampairs) paramsriap[id(npp_j)] = len(parampairs) parampairs.append((npp_i, npp_j)) linearparams.sort() return linearparams, parampairs, paramsriap # >>>