def newDatastore(self): lastDir = self.settings.getLastDir() if not lastDir: lastDir = "" path = "" name = "" append = True if self.datastore_type == 0: path = QtGui.QFileDialog.getExistingDirectory(self, "Select shape files folder ", lastDir) if path.strip()!="": path = unicode(path) name = os.path.basename(path) elif self.datastore_type == 1: path = QtGui.QFileDialog.getSaveFileName(self, "Create Spatialite data base", lastDir, "Spatialite (*.sqlite *.db)") if path.strip()!="": path = unicode(path) name = os.path.basename(path) #check if datastore with same name exists if self.datastores and name in self.datastores['name']: self.iface.messageBar().pushMessage("Error","A database already exists with the same name.",level = 1,duration = 5) #if not, create new connection in registry else: uf.createSpatialiteConnection(name, path) uf.createSpatialiteDatabase(path) if path != "" and name != "": #store the path used self.settings.setLastDir(path) if append: self.appendDatastoreList(name, path) self.setDatastore()
def command(self): config = self.session.config args = self.args[:] ops = [] for var in self.data.keys(): parts = ('.' in var) and var.split('.') or var.split('/') if parts[0] in config.rules: ops.append((var, self.data[var])) if self.args: arg = ' '.join(self.args) if '=' in arg: # Backwards compatiblity with the old 'var = value' syntax. var, value = [s.strip() for s in arg.split('=', 1)] var = var.replace(': ', '.').replace(':', '.').replace(' ', '') else: var, value = arg.split(' ', 1) ops.append((var, value)) for path, value in ops: value = value.strip() if value.startswith('{') or value.startswith('['): value = json.loads(value) try: cfg, var = config.walk(path.strip(), parent=1) cfg[var] = value except IndexError: cfg, v1, v2 = config.walk(path.strip(), parent=2) cfg[v1] = {v2: value} self._serialize('Save config', lambda: config.save()) return True
def FindNode(self,path): if path is None or len(path.strip())==0: return XmlNode(None,self.rootNode) path = path.strip() node = None if path[0]=='/': node = self.rootNode.find(path[1:]) else: node = self.currentNode.find(path) return XmlNode(node,self.rootNode)
def in_path(program): """Checks whether a program, like java, is in path (automatically checks for program and program.exe)""" for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path.strip('"'), program) if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK): return True exe_file = os.path.join(path.strip('"'), program + ".exe") if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK): return True return False
def __init__(self): self._filter_paths = {} display = self.env.config.get('timeline-checkin-filter', 'filter_paths', '') display = display.strip() display = display.split(',') for path in display: path = path.strip() path = path.split(':') label = path[0] path = path[1] if path: path = path.strip(os.sep) self._filter_paths[label] = path
def findPath(): try: path = str(raw_input("inserire il path assoluto del file >")) path.strip() if(os.path.isfile(path) != True or ((path.find("war") == -1) and (path.find("ear") == -1))): raise EapManagerException("ERRORE: il percorso non punta a un file valido") name = str(raw_input("inserire il nome dell'applicazione >")) return (path,name) except ValueError: raise EapManagerException("ERRORE: Inserire una stringa")
def path_to_sfd(path): # convert svg path syntax into sfd # written for conciseness, not efficiency x0, y0 = 0, 0 fre = re.compile(r'(\-?[0-9\.]+)\s*,?\s*') while path.strip() != '': path = path.strip() if path[0].isalpha(): cmd = path[0] path = path[1:].lstrip() args = [] for i in range(num_args_cmd(cmd)): m = fre.match(path) if m is None: print 'no float match:', path args.append(float(m.group(1))) path = path[m.end():] #print cmd, args if cmd.upper() == 'M': if cmd.islower(): (x, y), args = apply_rel_xy([x, y], args) x0, y0 = args print_one_cmd('m', args) x, y = args[-2:] if cmd == 'm': cmd = 'l' elif cmd == 'M': cmd = 'L' elif cmd.upper() in 'CLVHS': if cmd == 'H': args = args + [y] cmd = 'L' elif cmd == 'h': args = args + [0] cmd = 'l' if cmd == 'V': args = [x] + args cmd = 'L' elif cmd == 'v': args = [0] + args cmd = 'l' if cmd.islower(): args = apply_rel_xy([x, y], args) if cmd.upper() == 'S': # smooth curveto; reflect args = [2 * x - xs, 2 * y - ys] + args cmd = 'c' print_one_cmd(cmd.lower(), args) x, y = args[-2:] if len(args) > 2: xs, ys = args[-4:-2] elif cmd.upper() == 'Z': if x != x0 or y != y0: print_one_cmd('l', [x0, y0])
def _joinpath(self, root, path): if os.sep == '/': # on linux path = path.replace('\\', '/').strip('./') # change windows path to linux return os.path.join(root, path) else: # Assume on Windows path = path.strip('.\\') return os.path.join(root, path)
def _iterate_regionfiles(self,regionlist=None): """Returns an iterator of all of the region files, along with their coordinates Note: the regionlist here will be used to determinte the size of the world. Returns (regionx, regiony, filename)""" join = os.path.join if regionlist is not None: for path in regionlist: path = path.strip() f = os.path.basename(path) if f.startswith("r.") and f.endswith(".mcr"): p = f.split(".") logging.debug("Using path %s from regionlist", f) yield (int(p[1]), int(p[2]), join(self.worlddir, 'region', f)) else: logging.warning("Ignore path '%s' in regionlist", f) else: for path in glob(os.path.join(self.worlddir, 'region') + "/r.*.*.mcr"): dirpath, f = os.path.split(path) p = f.split(".") yield (int(p[1]), int(p[2]), join(dirpath, f))
def extract_path(self, context): path = context.request.path assert path.startswith(self.root._webpath) path = path[len(self.root._webpath):] path = path.strip('/').split('/') for dataformat in self.dataformats: if path[-1].endswith('.' + dataformat): path[-1] = path[-1][:-len(dataformat) - 1] # Check if the path is actually a function, and if not # see if the http method make a difference # TODO Re-think the function lookup phases. Here we are # doing the job that will be done in a later phase, which # is sub-optimal for p, fdef in self.root.getapi(): if p == path: return path # No function at this path. Now check for function that have # this path as a prefix, and declared an http method for p, fdef in self.root.getapi(): if len(p) == len(path) + 1 and p[:len(path)] == path and \ fdef.extra_options.get('method') == context.request.method: return p return path
def statNames(): #by year before 2014 will be better(less redundant info) #stopwords = ('pok','meet','of','the','with','he','i','she','this') stat = open('./ByYear/statByYear.txt','w') #path = r'./' for parent,dirs,files in os.walk(r'./ByYear/'): for d in dirs: #each day namedict = {} path = os.path.join(parent,d) stat.write(path.strip('.').strip('./')+':\n') for _parent,_dirs,_files in os.walk(path): for f in _files: if str(f)=='.DS_Store': continue s = os.path.join(_parent,f) f = open(s,'r') for line in f: for word in line.replace('"',' ').replace("'",' ').replace('-',' ').replace('<',' ').replace(':',' ').replace(',',' ').replace('.',' ').replace('!',' ').replace('(',' ').replace(')',' ').replace('[',' ').replace(']',' ').split(): if word.lower()!=word : key = word if key.lower() not in stopwords: if namedict.has_key(key): namedict[key] += 1 else: namedict[key] = 1 toBeDel = [] for key in namedict.keys(): if namedict[key]<=2 : toBeDel.append(key) for key in toBeDel: del(namedict[key]) stat.write(str(namedict).replace("'",'"')+'\n')
def which( program ): # Tries to locate a program import os if os.name == 'nt': program_ext = os.path.splitext( program )[1] if program_ext == "": prog_exe = which( program + ".exe" ) if prog_exe != None: return prog_exe return which( program + ".com" ) def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def is_preferred_browser(test): # We will import only if the user's preferred browser is mozilla http_handler = get_preferred_browser() if http_handler == None: return False if http_handler.find(test) != -1: return True paths = [path for path in os.getenv("PATH").split(os.path.pathsep) if path.strip() != "" and os.path.exists(path) and os.path.isdir(path)] for directory in paths: if http_handler.startswith("/"): program_path = http_handler else: program_path = os.path.join(directory, http_handler) while os.path.islink(program_path): program_path = os.path.join(directory, os.readlink(program_path)) directory = os.path.dirname(program_path) if program_path.find(test) != -1: return True return False
def __call__(self, environ, start_response): """Process trac request URLs are in the form of /project """ path = environ.get('PATH_INFO', '') user = self.authenticator(environ) project = None try: pathparts = path.strip('/').split('/') project = pathparts[0] project = self.cydra.get_project(project) if project is None: logger.debug("Unknown project: %s", path) start_response('404 Not Found', [('Content-Type', 'text/plain')]) return 'Unknown Project' if not os.path.exists(os.path.join(self.config['base'], project.name)): logger.debug("No trac found for: %s", project.name) start_response('404 Not Found', [('Content-Type', 'text/plain')]) return 'No trac environment found' if (len(pathparts) == 2 and pathparts[1] == 'login') and user.is_guest: return self.require_authorization(environ, start_response) return self.trac(environ, start_response) except Exception as e: logger.exception("Exception during Trac dispatch") start_response('404 Not Found', [('Content-Type', 'text/plain')]) return 'Unknown Trac/Project or invalid URL'
def selectFile(self): last_dir = uf.getLastDir("SDSS") path = QtGui.QFileDialog.getSaveFileName(self, "Save map file", last_dir, "PNG (*.png)") if path.strip()!="": path = unicode(path) uf.setLastDir(path,"SDSS") self.saveMapPathEdit.setText(path)
def FindNodes(self,path): if path is None or len(path.strip())==0: return XmlNode(None,self.rootNode) if path[0]=='/': nodes = self.rootNode.findall(path[1:]) else: nodes = self.currentNode.findall(path) return [XmlNode(node,self.rootNode) for node in nodes]
def fix_prefix(path, new_prefix=iphoto_dir): if path: if path[:len(path_prefix)] != path_prefix: raise AssertionError("Path %s didn't begin with %s" % (path, path_prefix)) path = path[len(path_prefix):] path = join_path(new_prefix, path.strip(os.path.sep)) return path
def post_build_find_installed_zope_interface_subdir_name(): # Mac OS X 10.5 Leopard includes twisted and twisted/zope.interface # We ignore this fact and want to find out the real directory name # of zope.interface installed in our `python_lib_dir'. # # Basically we do this and grep for zope.interface: # PYTHONPATH=`pwd`/pythonlib python -c 'import sys; print "\n".join(sys.path)' zope_interface_subdir_name = None cwd = DirectorySentinel(python_lib_dir) echo('Changed directory to %s', os.getcwd()) try: env = EnvironmentSentinel({'PYTHONPATH': os.getcwd()}) echo('Added %s into PYTHONPATH', os.getcwd()) try: cmd = "python -c \"import sys; print '\\n'.join(sys.path)\"" syspath = system_output(cmd) if syspath is not False: for path in syspath: path = path.strip() if re.match(r'.*/zope\.interface[^/]*$', path): zope_interface_subdir_name = os.path.basename(path) break finally: env.restore() finally: cwd.restore() if zope_interface_subdir_name is None: fail('Cannot deduce zope.interface real directory name in "python_lib_dir"') return zope_interface_subdir_name
def catchall(path): """The catch-all path handler. If it exists in the www folders, it's sent, otherwise we give the 404 error page.""" if path.endswith("/"): path = path.strip("/") # Remove trailing slashes. return redirect(path) # Search for this file. for root in [Config.site.site_root, "rophako/www"]: abspath = os.path.abspath("{}/{}".format(root, path)) if os.path.isfile(abspath): return send_file(abspath) # The exact file wasn't found, look for some extensions and index pages. suffixes = [ ".html", "/index.html", ".md", # Markdown formatted pages. "/index.md", ] for suffix in suffixes: if not "." in path and os.path.isfile(abspath + suffix): # HTML, or Markdown? if suffix.endswith(".html"): return rophako.utils.template(path + suffix) else: return rophako.utils.markdown_template(abspath + suffix) return not_found("404")
def command(self): config = self.session.config ops = [] if config.sys.lockdown: return self._error(_("In lockdown, doing nothing.")) for var in self.data.keys(): parts = ("." in var) and var.split(".") or var.split("/") if parts[0] in config.rules: ops.append((var, self.data[var][0])) if self.args: arg = " ".join(self.args) if "=" in arg: # Backwards compatible with the old 'var = value' syntax. var, value = [s.strip() for s in arg.split("=", 1)] var = var.replace(": ", ".").replace(":", ".").replace(" ", "") else: var, value = arg.split(" ", 1) ops.append((var, value)) updated = {} for path, value in ops: value = value.strip() if value.startswith("{") or value.startswith("["): value = json.loads(value) cfg, var = config.walk(path.strip(), parent=1) cfg[var].append(value) updated[path] = value self._serialize("Save config", lambda: config.save()) return self._success(_("Updated your settings"), result=updated)
def getJSONReportList(self, path='/Device Reports'): """ Given a report class path, returns a list of links to child reports in a format suitable for a TableDatasource. """ # This function will be monkey-patched onto zport, so # references to self should be taken as referring to zport # Add the base path to the path given path = '/zport/dmd/Reports/' + path.strip('/') # Create the empty structure of the response object response = { 'columns': ['Report'], 'data': [] } # Retrieve the ReportClass object for the path given. If # nothing can be found, return an empty response try: reportClass = self.dmd.unrestrictedTraverse(path) except KeyError: return json.dumps(response) # Get the list of reports under the class as (url, title) pairs reports = reportClass.reports() reportpairs = [(r.absolute_url_path(), r.id) for r in reports] # Iterate over the reports, create links, and append them to # the response object for url, title in reportpairs: link = "<a href='%s'>%s</a>" % (url, title) row = { 'Report': link } response['data'].append(row) # Serialize the response and return it return json.dumps(response)
def render_path_xml_buttons(self, request): """ The description of render_path_xml_buttons comes here. @param request @return """ # submit form and get result if not request.args.has_key('path'): return self.create_xml_response(1,'missing path').toxml() path = request.args.pop('path')[0] logger.weblog.debug('path: %s' % path) path = path.strip('/ ') # get object lst = path.split('/') #logger.weblog.debug('lst: %s' % str(lst)) (e,obj,sub) = self.srv.get_object(lst) #if not sub: # print "not sub: "+str(obj) # lst=lst[:-1] # path='/'.join(lst) if sub: obj = getattr(obj,sub) #logger.weblog.debug('obj: %s' % str(obj)) if obj != None: # empty obj is fine we need its static property ui_buttons btnsXML = buttons_generic(obj,path) (e,r) = (0, btnsXML) else: (e,r) = (1, 'object not found') return self.create_xml_response(e,r).toxml()
def which(cmd, env_path): cmd_is_list = isinstance(cmd, list) the_cmd = cmd[0] if cmd_is_list else cmd cmd_args = cmd[1:] if cmd_is_list else [] if os.path.isabs(the_cmd): return cmd with WHICH_CACHE as cache: cval = cache.get(the_cmd) if cval is not None: return [cval] + cmd_args if cmd_is_list else cval else: exe_exts = [''] if not Utils.is_windows() else ['.exe', '.cmd', '.bat'] program = the_cmd fpath, _ = os.path.split(program) if fpath: if is_exe(program): return cmd else: for path in env_path.split(os.pathsep): path = path.strip('"') for ext in exe_exts: exe_file = os.path.join(path, program) if is_exe(exe_file + ext): with WHICH_CACHE as cache: cache[program] = exe_file return [exe_file] + cmd_args if cmd_is_list else exe_file return None
def spawn(self, argv=None, term=None): if argv is None: if "SHELL" in os.environ: argv = [os.environ["SHELL"]] elif "PATH" in os.environ: # searching sh in the path. It can be unusual like /system/bin/sh on android for shell in ["bash", "sh", "ksh", "zsh", "csh", "ash"]: for path in os.environ["PATH"].split(":"): fullpath = os.path.join(path.strip(), shell) if os.path.isfile(fullpath): argv = [fullpath] break if argv: break if not argv: argv = ["/bin/sh"] if term is not None: os.environ["TERM"] = term master, slave = pty.openpty() self.slave = slave self.master = os.fdopen(master, "rb+wb", 0) # open file in an unbuffered mode flags = fcntl.fcntl(self.master, fcntl.F_GETFL) assert flags >= 0 flags = fcntl.fcntl(self.master, fcntl.F_SETFL, flags | os.O_NONBLOCK) assert flags >= 0 self.prog = subprocess.Popen( shell=False, args=argv, stdin=slave, stdout=slave, stderr=subprocess.STDOUT, preexec_fn=prepare )
def command(self): config = self.session.config args = self.args[:] ops = [] if config.sys.lockdown: self.session.ui.warning(_('In lockdown, doing nothing.')) return False for var in self.data.keys(): parts = ('.' in var) and var.split('.') or var.split('/') if parts[0] in config.rules: ops.append((var, self.data[var][0])) if self.args: arg = ' '.join(self.args) if '=' in arg: # Backwards compatible with the old 'var = value' syntax. var, value = [s.strip() for s in arg.split('=', 1)] var = var.replace(': ', '.').replace(':', '.').replace(' ', '') else: var, value = arg.split(' ', 1) ops.append((var, value)) for path, value in ops: value = value.strip() if value.startswith('{') or value.startswith('['): value = json.loads(value) cfg, var = config.walk(path.strip(), parent=1) cfg[var].append(value) self._serialize('Save config', lambda: config.save()) return True
def get_file(self, path): """<DOC> Returns the path to a file. First checks if the file is in the file pool # and then the folder of the current experiment (if any). Otherwise, # simply returns the path. Arguments: path -- The filename. Returns: The full path to the file. Example: >>> image_path = exp.get_file('my_image.png') >>> my_canvas = exp.offline_canvas() >>> my_canvas.image(image_path) </DOC>""" path = self.unistr(path) if path.strip() == u'': raise osexception( \ u"An empty string was passed to experiment.get_file(). Please specify a valid filename.") if os.path.exists(os.path.join(self.pool_folder, path)): return os.path.join(self.pool_folder, path) elif self.experiment_path != None and os.path.exists(os.path.join( \ self.experiment_path, path)): return os.path.join(self.experiment_path, path) else: return path
def get(self, path, with_body=True): filename = os.path.abspath(os.path.join(self.root, path.strip("/"))) if not filename.startswith(self.root): return response.Response(status.FORBIDDEN) elif not os.path.exists(filename): return response.Response(status.NOT_FOUND) if os.path.isdir(filename): body = None content_length = "0" if with_body: body = self._get_collection(filename) content_length = str(len(body)) return response.Response(status.OK, {"Content-Type": "text/html", "Content-Length": content_length}, [body] if with_body else None) else: st = os.stat(filename) headers = {"Content-Type": mimetypes.guess_type(filename)[0] or "application/octet-stream", "Content-Length": str(st.st_size)} return response.Response(status.OK, headers, FileIterator(filename) if with_body else None)
def _write_source(self, sourcecode, path, filename, tag): """ Write the decompiled sourcecode to disk location """ dump_dir = os.path.join(self.dump_dir, tag, path.strip(os.sep)) #TODO - cleanup self._quiet_makedir(dump_dir) location = os.path.join(dump_dir, filename) ext = os.path.splitext(location)[1] if ext == ".pyc": location = location.replace(".pyc",".py") elif ext == ".pyo": location = location.replace(".pyo", ".py") try: f = open(location, "wb") f.write(sourcecode) f.close() print "[+] Source code written to: %s"%location except Exception, err: print "[-] Problem writing sourcecode to %s [%s]"%(location, err)
def which(program): """ Find executable on path. Shamelessly borrowed from Jay, at http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python """ def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def put(self, path, content_length, body): filename = os.path.abspath(os.path.join(self.root, path.strip("/"))) if not filename.startswith(self.root): return response.Response(status.FORBIDDEN) elif os.path.isdir(filename): return response.Response(status.NOT_ALLOWED) elif not os.path.isdir(os.path.dirname(filename)): return response.Response(status.CONFLICT) created = not os.path.exists(filename) f = open(filename, "wb") if content_length: remaining = content_length while remaining > 0: buf = body.read(min(remaining, BLOCK_SIZE)) if len(buf): f.write(buf) remaining -= len(buf) else: break f.close() if created: return response.Response(status.CREATED) else: return response.Response(status.NO_CONTENT)
def which(program): import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def which(cmd): """Check if cmd is an executable in the system path.""" # modified from http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(cmd) if fpath: if is_exe(cmd): return cmd else: for path in os.environ['PATH'].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, cmd) if is_exe(exe_file): return exe_file return None
def action_upload(self, courseid, taskid, path, fileobj): """ Upload a file """ # the path is given by the user. Let's normalize it path = path.strip() if not path.startswith("/"): path = "/" + path wanted_path = self.verify_path(courseid, taskid, path, True) if wanted_path is None: return self.show_tab_file(courseid, taskid, _("Invalid new path")) task_fs = self.task_factory.get_task_fs(courseid, taskid) try: task_fs.put(wanted_path, fileobj.read()) except: return self.show_tab_file( courseid, taskid, _("An error occurred while writing the file")) return self.show_tab_file(courseid, taskid)
def which(program): """Test if program is pathed.""" # stackoverflow.com/questions/377017/test-if-executable-exists-in-python fpath = os.path.split(program)[0] if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def which(program): """ Find and return the given program by its absolute path or 'None' if the program cannot be found. From: http://stackoverflow.com/a/377028 """ fpath = os.path.split(program)[0] if fpath: if is_exe(program): return program else: for path in os.environ.get("PATH").split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def _find_executable_noext(leafname): """Helper function for find_executable.""" def is_exe(supplied_path): return os.path.isfile(supplied_path) and os.access(supplied_path, os.X_OK) supplied_path = os.path.split(leafname)[0] if supplied_path: if is_exe(leafname): return leafname else: logger.info("Looking for %s on %s" % (leafname, os.environ["PATH"])) for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, leafname) if is_exe(exe_file): return exe_file return None
def get_path(self, key='path'): """ 获取并处理path :return: """ parser = ParamsParser(self._request) path = parser.get_str(key, '') if path == "#" or path == "/" or path.strip() == '': path = "./" if path[:1] == "/": path = "." + path if '../' in path: raise WeJudgeError(3454) return path
def make_dataset_txt(path_files, root_dir): # reading txt file image_paths = [] with open(path_files) as f: paths = f.readlines() for path in paths: # path = path.strip() path = root_dir + path.strip() image_paths.append(path) min_n = 8000 if False: if len(image_paths) > min_n: image_paths = image_paths[:min_n] return image_paths, len(image_paths)
def which(program): 'It emulates the which Unix utility' def is_exe(fpath): 'The file is an executable' return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath = os.path.dirname(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def mkdir(path): # 去除首位空格 path = path.strip() if os.path.isabs(path): isExists = os.path.exists(path) # 判断结果 if not isExists: # 如果不存在则创建目录 # 创建目录操作函数 os.makedirs(path) return True else: # 获取当前Py文件所在路径 currentPath = os.getcwd() # 去除尾部 \ 符号 path = currentPath + '/' + path.rstrip("\\|/") os.makedirs(path)
def proper_windows_path(path, current_platform = sys.platform): """ This function takes an absolute Windows or Cygwin path and returns a path appropriately formatted for the platform it's running on (as determined by sys.platform)""" path = path.strip() drive_letter = None rel = None match = re.match("/cygdrive/([a-z])/(.*)", path) if(not match): match = re.match('([a-zA-Z]):\\\(.*)', path) if(not match): return None # not an absolute path drive_letter = match.group(1) rel = match.group(2) if(current_platform == "cygwin"): return "/cygdrive/" + drive_letter.lower() + '/' + rel.replace('\\', '/') else: return drive_letter.upper() + ':\\' + rel.replace('/', '\\')
def which(program): """Tests whether the specified program is present in the environment PATH hinting it probably exists.""" import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file
async def zip(event): if event.fwd_from: return input_str = event.pattern_match.group(1) path = input_str zip_name = "" if "|" in input_str: path, zip_name = path.split("|") path = path.strip() zip_name = zip_name.strip() if exists(path): await event.edit("`Zipping...`") start_time = datetime.now() if isdir(path): dir_path = path.split("/")[-1] if path.endswith("/"): dir_path = path.split("/")[-2] zip_path = join(TEMP_DOWNLOAD_DIRECTORY, dir_path) + ".zip" if zip_name: zip_path = join(TEMP_DOWNLOAD_DIRECTORY, zip_name) if not zip_name.endswith(".zip"): zip_path += ".zip" with ZipFile(zip_path, "w", ZIP_DEFLATED) as zip_obj: for roots, _, files in os.walk(path): for file in files: files_path = join(roots, file) arc_path = join(dir_path, relpath(files_path, path)) zip_obj.write(files_path, arc_path) end_time = (datetime.now() - start_time).seconds await event.edit( f"Zipped `{path}` into `{zip_path}` in `{end_time}` seconds." ) elif isfile(path): file_name = basename(path) zip_path = join(TEMP_DOWNLOAD_DIRECTORY, file_name) + ".zip" if zip_name: zip_path = join(TEMP_DOWNLOAD_DIRECTORY, zip_name) if not zip_name.endswith(".zip"): zip_path += ".zip" with ZipFile(zip_path, "w", ZIP_DEFLATED) as zip_obj: zip_obj.write(path, file_name) await event.edit(f"Zipped `{path}` into `{zip_path}`") else: await event.edit("`404: Not Found`")
def check_filepath(path): # 去除首位空格 path = path.strip() # 去除尾部 \ 符号 path = path.rstrip("\\") # 判断路径是否存在 # 存在 True # 不存在 False isExists = os.path.exists(path) # 判断结果 if not isExists: # 如果不存在则创建目录 os.makedirs(path) print(path + ' 创建成功') return True else: # 如果目录存在则不创建,并提示目录已存在 # print(path + ' 目录已存在') return False
def get_stylesheet_list(settings): """ Retrieve list of stylesheet references from the settings object. """ assert not (settings.stylesheet and settings.stylesheet_path), ( 'stylesheet and stylesheet_path are mutually exclusive.') stylesheets = settings.stylesheet_path or settings.stylesheet or [] # programmatically set default may be string with comma separated list: if not isinstance(stylesheets, list): stylesheets = [path.strip() for path in stylesheets.split(',')] if settings.stylesheet_path: # expand relative paths if found in stylesheet-dirs: stylesheets = [ find_file_in_dirs(path, settings.stylesheet_dirs) for path in stylesheets ] if os.sep != '/': # for URLs, we need POSIX paths stylesheets = [path.replace(os.sep, '/') for path in stylesheets] return stylesheets
def which(program): """Return path of program or None, see http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python""" import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def find_profile(create=True, path=''): """ Finds the newest profile in a specified directory. """ path = path.strip() if path == '': path = os.getcwd() highest = 0 for file in os.listdir(path): if (file[:9] == 'profiler_') and (file[-5:] == '.prof'): try: highest = max(highest, int(file[9:-5])) except: pass if create: highest += 1 return os.path.join(path, 'profiler_%d.prof' % highest)
def init(config, path): """ init module of linchpin """ click.echo('Initailising the templates for linchpin file !') if checkpaths(): reply = display("WARNING:001", "prompt") if not reply: sys.exit(0) if config.verbose: click.echo("### verbose mode ###") if os.path.isdir(path): path = path.strip("/") config.linchpinfile.stream().dump(path + '/' + 'PinFile') mkdir(path + "/topologies") mkdir(path + "/layouts") mkdir(path + "/inventories") dir_list = ["topologies", "layouts"] copy_files(path, dir_list, config) else: click.echo("Invalid path to initialize !!")
def which(program): """Trova il path assoluto per il file eseguibile di un comando :param str program: Il nome con cui viene invocato il programma """ def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): # noqa path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def action_create(self, courseid, taskid, path): """ Delete a file or a directory """ # the path is given by the user. Let's normalize it path = path.strip() if not path.startswith("/"): path = "/" + path want_directory = path.endswith("/") wanted_path = self.verify_path(courseid, taskid, path, True) if wanted_path is None: return self.show_tab_file(courseid, taskid, _("Invalid new path")) task_fs = self.task_factory.get_task_fs(courseid, taskid) if want_directory: task_fs.from_subfolder(wanted_path).ensure_exists() else: task_fs.put(wanted_path, b"") return self.show_tab_file(courseid, taskid)
def _build_paths(self, path, depth): path = path.strip("/") path = os.path.abspath(os.path.join(self.root, path)) if path.startswith(self.root) and os.path.exists(path): paths = [path] if os.path.isdir(path) and depth == 1: for p in os.listdir(path): if self._show(p): paths.append(os.path.join(path, p)) for i, p in enumerate(paths): if os.path.isdir(p) and p[:-1] != "/": paths[i] = p + "/" return paths raise IOError
def cleanUpPath(path): """ This function 1) Removes extra beginning/trailing quotes, spaces and newlines. 2) Appends $PROJ_DIR$ to all paths. All paths are assumed to be relative to the Makefile. 3) Normalizes the paths. Returns a clean up path. """ # Remove extra quotes and spaces cleanPath = path.strip() cleanPath = cleanPath.strip("\"") # The normalize operation needs to happen before prepend project directory # variable operation. After appending the placeholder variable to the output # is not a standard path so the normalize operation does not work correctly. cleanPath = ntpath.normpath(cleanPath) # Append project dir cleanPath = ntpath.join(PROJ_DIR_STR, cleanPath) return cleanPath
def which(program): """Works exactly like the unix command which Courtesy of http://stackoverflow.com/a/377028/675646""" def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def searchPath(self, path, typ): data = None elm = self.path[len(self.path)-1] elm = elm.getChildren() if elm is not None: keys = list(elm.keys()) i = 0 while data is None and i < len(keys): if str(elm[keys[i]].getName()).strip() == path.strip() and ( (isinstance(elm[keys[i]], SugarSyncDirectory) and typ == SugarSyncShell.TYPE_FOLDER) or (isinstance(elm[keys[i]], SugarSyncFile) and typ == SugarSyncShell.TYPE_FILE) or typ == SugarSyncShell.TYPE_ALL ): data = elm[keys[i]] i = i+1 return data
def py_tokenize(self, base_dir, file_name): # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from io import BytesIO from tokenize import COMMENT, ENCODING, ENDMARKER, INDENT, NEWLINE, NL, NUMBER, STRING, tokenize file_paths = open(os.path.join(base_dir, file_name), encoding="utf-8").readlines() for ct, path in enumerate(file_paths): try: code = open(os.path.join(base_dir, path.strip()), encoding="utf-8").read() token_gen = tokenize(BytesIO(bytes(code, "utf8")).readline) out_tokens = [] prev_eol = False for toknum, tokval, _, _, _ in token_gen: tokval = " ".join(tokval.split()) if len(tokval) > 100: continue if toknum == STRING: add_token = self.process_string(tokval) if len(add_token) > 0: out_tokens.append(add_token) prev_eol = False elif toknum == NUMBER: if len(tokval) < 50: out_tokens.append(tokval) prev_eol = False elif toknum in [NEWLINE, NL]: if not prev_eol: out_tokens.append("<EOL>") prev_eol = True elif toknum in [COMMENT, INDENT, ENCODING, ENDMARKER] or len(tokval) == 0: continue else: out_tokens.append(tokval) prev_eol = False if out_tokens[0] == "<EOL>": out_tokens = out_tokens[1:] if out_tokens[-1] == "<EOL>": out_tokens = out_tokens[:-1] except Exception: out_tokens = [] out_tokens = ["<s>"] + out_tokens + ["</s>"] yield path, out_tokens
def cd(self, path): """cd to specified path. Bound to `cdg` in IPython shell. `path` can be relative or absolute. To use autocompletion of path command should be invoked with prepended semicolon in ipython shell as ;cdg /path """ if path.strip() == '..': self.context = self.context.__parent__ self.update_ns() return self.pwd # cd self.context = get_context_by_path(self.get_start_context(path), path) self.update_ns() return self.pwd
def get_file_pos(self, path): #path = path.upper().strip('/').split('/') path = path.strip('/').split('/') path, filename = path[:-1], path[-1] if len(path) == 0: parent_dir = self._root else: try: parent_dir = self._dir_record_by_table(path) except ISO9660IOError: try: parent_dir = self._dir_record_by_root(path) except: return None f = self._search_dir_children(parent_dir, filename) return (f['ex_loc'], f['ex_len'])
def which(program): '''Tests if a given command line tool is available, replicating the "which" function''' import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def savePath(): try: path = pa.SaveDialog(msgDict["SaveDialog"], "", "~/") if path is None: return None # trying to add ".shp" to the end of the path if it is not included path = path.strip() if path.rfind(".shp") != (len(path) - len(".shp")): if path.rfind(".") != (len(path) - 1): path += ".shp" else: path += "shp" if path.count(".") > 1: pa.MessageBox(msgDict["FileNameErr"], "Error") return None return path except Exception as e: printErrorMessage(e) return None
def get_file(self, path): """ desc: | Returns the full path to a file. The logic is as follows: 1. First checks if `path` is a file in the file pool. 2. If not, check if `path` is a file in the folder of the current experiment (if any). 3. If not, check if `path` is a file in the `__pool__` subfolder of the current experiment. 4. If not, simply return `path`. arguments: path: desc: A filename. This can be any type, but will be coerced to `unicode` if it is not `unicode`. returns: desc: The full path to the file. type: unicode example: | image_path = exp.get_file('my_image.png') my_canvas = exp.offline_canvas() my_canvas.image(image_path) """ path = self.unistr(path) if path.strip() == u'': raise osexception( u"An empty string was passed to experiment.get_file(). Please " u"specify a valid filename.") if os.path.exists(os.path.join(self.pool_folder, path)): return os.path.join(self.pool_folder, path) if self.experiment_path != None: if os.path.exists(os.path.join(self.experiment_path, path)): return os.path.join(self.experiment_path, path) if self.fallback_pool_folder != None and os.path.exists( os.path.join(self.experiment_path, self.fallback_pool_folder, path)): return os.path.join(self.experiment_path, self.fallback_pool_folder, path) return path