Python os.path.strip() Examples

The following are code examples for showing how to use os.path.strip(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: raspberry-pi-scripts   Author: vermer   File: napi.py    (license) View Source Project 6 votes vote down vote up
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 
Example 2
Project: python-mrcz   Author: em-MRCZ   File: test_mrcz.py    (license) View Source Project 6 votes vote down vote up
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 
Example 3
Project: crawlpy   Author: cytopia   File: crawlpy-login.py    (license) View Source Project 6 votes vote down vote up
def which(program):
        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

    #---------------------------------------------------------------------- 
Example 4
Project: zorro   Author: C-CINA   File: zorro_util.py    (license) View Source Project 6 votes vote down vote up
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 
Example 5
Project: LMS   Author: RRZE-HPC   File: influxdbHandlerNative.py    (license) View Source Project 6 votes vote down vote up
def which(program):
    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 
Example 6
Project: LMS   Author: RRZE-HPC   File: influxdbHandlerNative.py    (license) View Source Project 6 votes vote down vote up
def read_tags(self):
        tags = {}
        if loggedin_users(self.userblacklist) == 0 and os.path.exists(self.tagfile):
            os.remove(self.tagfile)
            return tags
        if os.path.exists(self.tagfile):
            finput = None
            try:
                f = open(self.tagfile)
                finput = f.read().strip()
                f.close()
            except:
                self.log.error("Cannot open tag file %s" % (self.tagfile,))
                return tags
            for line in finput.split("\n"):
                if line.startswith("#") or not line.strip():
                    continue
                if not ":" in line:
                    continue
                linelist = [ i.strip() for i in line.split(":") ]
                if len(linelist):
                    tags.update({linelist[0] : linelist[1]})
        return tags 
Example 7
Project: chewBBACA_deprecated   Author: mickaelsilva   File: CreateSchema.py    (license) View Source Project 6 votes vote down vote up
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 True
    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 True

    return "Not found" 
Example 8
Project: dancedeets-monorepo   Author: mikelambert   File: serve.py    (license) View Source Project 6 votes vote down vote up
def get(self):
        root = etree.Element('sitemapindex')
        root.attrib['xmlns'] = 'http://www.sitemaps.org/schemas/sitemap/0.9'

        bucket_name = 'dancedeets-hrd.appspot.com'
        bucket = client.get_bucket(bucket_name)

        recent_date = get_mapreduce_date(bucket, 'Generate FUTURE Sitemaps')
        root.append(sitemap_node('recent', recent_date))

        versioned_date = get_mapreduce_date(bucket, 'Generate Sitemaps')
        path = get_newest_path(bucket, 'Generate Sitemaps')
        version = os.path.basename(path.strip('/'))
        print path, version
        for i in range(MapReduceShards):
            root.append(sitemap_node('%s-%s' % (version, i), versioned_date))

        root_data = etree.tostring(root, pretty_print=True)

        self.response.headers["Content-Type"] = "text/xml"
        self.response.out.write(root_data) 
Example 9
Project: chewBBACA   Author: B-UMMI   File: CreateSchema.py    (license) View Source Project 6 votes vote down vote up
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 True
    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 True

    return "Not found" 
Example 10
Project: PyPPL   Author: pwwang   File: testFlowchart.py    (license) View Source Project 6 votes vote down vote up
def which(program):
	import os
	def is_exe(fpath):
		return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

	fpath, _ = 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 
Example 11
Project: PyPPL   Author: pwwang   File: testPyPPL.py    (license) View Source Project 6 votes vote down vote up
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 
Example 12
Project: PyPPL   Author: pwwang   File: testRunners.py    (license) View Source Project 6 votes vote down vote up
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 
Example 13
Project: Netkeeper   Author: 1941474711   File: AppXml.py    (license) View Source Project 5 votes vote down vote up
def LoadString(self, data):
        if data is None or len(data.strip()) == 0: return False
        flag = False
        try:
            self.rootNode = ElementTree.fromstring(data)
            if self.rootNode is not None: flag = True
            self.currentNode = self.rootNode
        except Exception, e:
            logging.error("XML??????")
            logging.error(e.__str__())
        return flag

    #  ?????????? 
Example 14
Project: Netkeeper   Author: 1941474711   File: AppXml.py    (license) View Source Project 5 votes vote down vote up
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)

    # ????? 
Example 15
Project: Netkeeper   Author: 1941474711   File: AppXml.py    (license) View Source Project 5 votes vote down vote up
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]

    # ??????? 
Example 16
Project: Netkeeper   Author: 1941474711   File: AppXml.py    (license) View Source Project 5 votes vote down vote up
def GetChildrenMap(self, tag=None, keyType=XmlNodeMap.ATTR, keyName="name", valueType=XmlNodeMap.TEXT,
                       valueName=None, valueFormat=XmlNodeValue.STRING):
        data = {}
        for node in self.GetChildrens(tag=tag):
            k, v = None, None
            if keyType == XmlNodeMap.ATTR:
                if keyName is None or len(keyName.strip()) == 0: continue
                k = node.GetAttrs().GetStr(keyName)
            elif keyType == XmlNodeMap.NODE:
                if keyName is None or len(keyName.strip()) == 0: continue
                t = node.FindNode(keyName)
                if not t.IsLoad(): continue
                k = t.GetStr()
            elif keyType == XmlNodeMap.TEXT:
                k = node.GetStr()
            else:
                continue
            if k is None or len(k.strip()) == 0: continue
            if valueType == XmlNodeMap.ATTR:
                if valueName is None or len(valueName.strip()) == 0: continue
                v = self.GetFormatData(node.GetAttrs(), valueFormat)
            elif valueType == XmlNodeMap.NODE:
                if valueName is None or len(valueName.strip()) == 0: continue
                t = node.FindNode(valueName)
                if t.IsLoad():
                    v = self.GetFormatData(t, valueFormat)
            elif valueType == XmlNodeMap.TEXT:
                v = self.GetFormatData(node, valueFormat)
            else:
                v = None
            data[k] = v
        return data

    # ?????? 
Example 17
Project: Netkeeper   Author: 1941474711   File: AppXml.py    (license) View Source Project 5 votes vote down vote up
def GetStr(self, default="", strip=True):
        data = self.GetData()
        if data is None: return default
        try:
            data = str(data.encode("utf-8"))
            if data is None:
                data = default
            else:
                if strip:
                    data = data.strip()
        except Exception, e:
            print e
            data = default
        return data 
Example 18
Project: OSPTF   Author: xSploited   File: ptyshell.py    (license) View Source Project 5 votes vote down vote up
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
        ) 
Example 19
Project: aws-cfn-plex   Author: lordmuffin   File: __init__.py    (license) View Source Project 5 votes vote down vote up
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 can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 20
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    (license) View Source Project 5 votes vote down vote up
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 can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 21
Project: docket   Author: rocknsm   File: pcap.py    (license) View Source Project 5 votes vote down vote up
def _parseDuration(s):
    from flask import current_app
    logger = current_app.logger
    from datetime import timedelta

    for timefmt in TIMEFORMATS:
        logger.debug("timefmt is {}".format(timefmt))
        match = re.match(r'\s*' + timefmt + r'\s*$', s, re.I)
        logger.debug("Match is {}".format(match))
        if match and match.group(0).strip():
    	    mdict = match.groupdict()
    	    logger.debug("mdict is {}".format(mdict))
    	    return timedelta(seconds=sum(
    	        [MULTIPLIERS[k] * float(v) for (k, v) in
    	    	list(mdict.items()) if v is not None])) 
Example 22
Project: pupy   Author: ru-faraon   File: ptyshell.py    (license) View Source Project 5 votes vote down vote up
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
        ) 
Example 23
Project: chalktalk_docs   Author: loremIpsum1771   File: __init__.py    (license) View Source Project 5 votes vote down vote up
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 can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 24
Project: spark-yarn-rest-api   Author: bernhard-42   File: spark-remote-submit.py    (license) View Source Project 5 votes vote down vote up
def createHdfsPath(path):
    return os.path.join("hdfs://", hadoopNameNode, path.strip("/")) 
Example 25
Project: spark-yarn-rest-api   Author: bernhard-42   File: spark-remote-submit.py    (license) View Source Project 5 votes vote down vote up
def webhdfsGetRequest(path, op, allow_redirects=False):
    url = os.path.join(hadoopWebhdfsHost, path.strip("/"))
    response = requests.get("%s?op=%s" % (url, op), allow_redirects=allow_redirects, verify=validateKnoxSSL, auth=(username, password))
    print ">>> Status: %d (%s)" % (response.status_code, url)
    return response.json() 
Example 26
Project: spark-yarn-rest-api   Author: bernhard-42   File: spark-remote-submit.py    (license) View Source Project 5 votes vote down vote up
def webhdfsPutRequest(path, op, allow_redirects=False):
    url = os.path.join(hadoopWebhdfsHost, path.strip("/"))
    response = requests.put("%s?op=%s" % (url, op), "", allow_redirects=allow_redirects, verify=validateKnoxSSL, auth=(username, password))
    print ">>> Status: %d (%s)" % (response.status_code, url)
    return response 
Example 27
Project: MyKnowledge   Author: guofei9987   File: file2tree.py    (license) View Source Project 5 votes vote down vote up
def get_deepth(path):
    plat_sys = platform.system()
    deepth = 0
    if plat_sys == "Windows":
        path = path.strip("\\")
        deepth = path.count("\\") + 1
    elif plat_sys == "Linux":
        path = path.strip("/")
        deepth = path.count("/") + 1
    return deepth 
Example 28
Project: ukui-menu   Author: ukui   File: easyfiles.py    (license) View Source Project 5 votes vote down vote up
def GetFilePath(uri):
		path = urllib.request.url2pathname(uri) # escape special chars
		path = path.strip('\r\n\x00') # remove \r\n and NULL

		# get the path to file
		if path.startswith('file://'): # nautilus, rox
			path = path[7:] # 7 is len('file://')
		return path 
Example 29
Project: maze-builder   Author: kcsaff   File: processor.py    (license) View Source Project 5 votes vote down vote up
def process_pov(self, filename):
        if not self.args or not self.args.pov:
            if self.verbose > 0:
                print('No POV handler registered, pipeline stopping')
            return

        pov_args = [
            self.args.pov,
        ]
        if self.args.ini:
            ini = random.choice(self.args.ini.split(',')).strip()
            if ini.endswith('[]'):
                section = random.choice(read_ini_sections(ini[:-2]))
                ini = '{}[{}]'.format(ini[:-2], section)
            pov_args.append(ini)
        else:
            # Default size
            pov_args.extend(['+W1024', '+H768'])
        if self.args.include_path:
            pov_args.extend('+L{}'.format(path.strip()) for path in self.args.include_path.split(','))
        pov_args.extend([
            '+I{}'.format(filename),
            '+O{}'.format(OUT_FILENAME),
            '-P', '-D', '-V', '+FN8'
        ])

        with timed(is_verbose(1), 'POV-Ray is rendering maze...', 'Maze rendered in {0:.3f}s'):
            subprocess.check_call(pov_args)

        if self.args.keys:
            self.tweet(filename=OUT_FILENAME) 
Example 30
Project: blackmamba   Author: zrzka   File: __init__.py    (license) View Source Project 5 votes vote down vote up
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 can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 31
Project: RST-vscode   Author: tht13   File: __init__.py    (license) View Source Project 5 votes vote down vote up
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 can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 32
Project: starfuse   Author: Qix-   File: vfs.py    (license) View Source Project 5 votes vote down vote up
def _split_path(self, path):
        return path.strip(os.sep).split(os.sep) 
Example 33
Project: PyPPL   Author: pwwang   File: testPyPPL.py    (license) View Source Project 5 votes vote down vote up
def testRun(self):
		"""
		         / p3  --- \ 
		p1 -- p2            \    / p8
		  \      \ p4 \       p7 
		    p10         p6  /    \ p9
		           p5 /
		"""
		from collections import OrderedDict
		ProcTree.NODES = OrderedDict()
		p1  = Proc()
		p2  = Proc()
		p3  = Proc()
		p4  = Proc()
		p5  = Proc()
		p6  = Proc()
		p7  = Proc()
		p8  = Proc()
		p9  = Proc()
		p10 = Proc()
		p1.profile = 'proc'
		p2.addDepends(p1)
		p10.addDepends(p1)
		p3.addDepends(p2)
		p4.addDepends(p2)
		p6.addDepends(p4, p5)
		p7.addDepends(p3, p6)
		p8.addDepends(p7)
		p9.addDepends(p7)

		with captured_output() as (out, err):
			PyPPL(config = {
				'log': {
					'levels': 'all',
					'file': None
				}
			}).start(p1, p5).run()
		errmsgs = [e for e in err.getvalue().splitlines() if 'SUBMIT' in e]
		errmsgs = [e[(e.index('Running')+8):-4].strip() for e in errmsgs]
		self.assertEqual(errmsgs, ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'p10']) 
Example 34
Project: RemoteCpp   Author: ruibm   File: RemoteCpp.py    (license) View Source Project 5 votes vote down vote up
def normalise_path(path):
  path = path.strip()
  if path.startswith('./'):
    path = path[2:]
  return path 
Example 35
Project: RemoteCpp   Author: ruibm   File: RemoteCpp.py    (license) View Source Project 5 votes vote down vote up
def _is_valid_path(self, line):
    if line == None:
      return False
    line = line.strip()
    return len(line) > 0 and not line.startswith('#') 
Example 36
Project: RemoteCpp   Author: ruibm   File: RemoteCpp.py    (license) View Source Project 5 votes vote down vote up
def to_args(view):
    parts = [s.strip() for s in view.name().split('-')]
    if len(parts) == 1:
      return {}
    elif len(parts) == 2:
      return { 'prefix': parts[1] }
    else:
      raise Exception('Not a ListFiles window {0}.'.format(view.name())) 
Example 37
Project: tf_aws_ecs_instance_draining_on_scale_in   Author: terraform-community-modules   File: __init__.py    (license) View Source Project 5 votes vote down vote up
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 can be string or unicode:
    if not isinstance(stylesheets, list):
        stylesheets = [path.strip() for path in stylesheets.split(',')]
    # expand relative paths if found in stylesheet-dirs:
    return [find_file_in_dirs(path, settings.stylesheet_dirs)
            for path in stylesheets] 
Example 38
Project: mate-menu   Author: ubuntu-mate   File: easyfiles.py    (license) View Source Project 5 votes vote down vote up
def GetFilePath(uri):
		path = urllib.url2pathname(uri) # escape special chars
		path = path.strip('\r\n\x00') # remove \r\n and NULL

		# get the path to file
		if path.startswith('file://'): # nautilus, rox
			path = path[7:] # 7 is len('file://')
		return path 
Example 39
Project: aws-cfn-plex   Author: lordmuffin   File: __init__.py    (license) View Source Project 4 votes vote down vote up
def extract_name_value(line):
    """
    Return a list of (name, value) from a line of the form "name=value ...".

    :Exception:
        `NameValueError` for invalid input (missing name, missing data, bad
        quotes, etc.).
    """
    attlist = []
    while line:
        equals = line.find('=')
        if equals == -1:
            raise NameValueError('missing "="')
        attname = line[:equals].strip()
        if equals == 0 or not attname:
            raise NameValueError(
                  'missing attribute name before "="')
        line = line[equals+1:].lstrip()
        if not line:
            raise NameValueError(
                  'missing value after "%s="' % attname)
        if line[0] in '\'"':
            endquote = line.find(line[0], 1)
            if endquote == -1:
                raise NameValueError(
                      'attribute "%s" missing end quote (%s)'
                      % (attname, line[0]))
            if len(line) > endquote + 1 and line[endquote + 1].strip():
                raise NameValueError(
                      'attribute "%s" end quote (%s) not followed by '
                      'whitespace' % (attname, line[0]))
            data = line[1:endquote]
            line = line[endquote+1:].lstrip()
        else:
            space = line.find(' ')
            if space == -1:
                data = line
                line = ''
            else:
                data = line[:space]
                line = line[space+1:].lstrip()
        attlist.append((attname.lower(), data))
    return attlist 
Example 40
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    (license) View Source Project 4 votes vote down vote up
def extract_name_value(line):
    """
    Return a list of (name, value) from a line of the form "name=value ...".

    :Exception:
        `NameValueError` for invalid input (missing name, missing data, bad
        quotes, etc.).
    """
    attlist = []
    while line:
        equals = line.find('=')
        if equals == -1:
            raise NameValueError('missing "="')
        attname = line[:equals].strip()
        if equals == 0 or not attname:
            raise NameValueError(
                  'missing attribute name before "="')
        line = line[equals+1:].lstrip()
        if not line:
            raise NameValueError(
                  'missing value after "%s="' % attname)
        if line[0] in '\'"':
            endquote = line.find(line[0], 1)
            if endquote == -1:
                raise NameValueError(
                      'attribute "%s" missing end quote (%s)'
                      % (attname, line[0]))
            if len(line) > endquote + 1 and line[endquote + 1].strip():
                raise NameValueError(
                      'attribute "%s" end quote (%s) not followed by '
                      'whitespace' % (attname, line[0]))
            data = line[1:endquote]
            line = line[endquote+1:].lstrip()
        else:
            space = line.find(' ')
            if space == -1:
                data = line
                line = ''
            else:
                data = line[:space]
                line = line[space+1:].lstrip()
        attlist.append((attname.lower(), data))
    return attlist 
Example 41
Project: chalktalk_docs   Author: loremIpsum1771   File: __init__.py    (license) View Source Project 4 votes vote down vote up
def extract_name_value(line):
    """
    Return a list of (name, value) from a line of the form "name=value ...".

    :Exception:
        `NameValueError` for invalid input (missing name, missing data, bad
        quotes, etc.).
    """
    attlist = []
    while line:
        equals = line.find('=')
        if equals == -1:
            raise NameValueError('missing "="')
        attname = line[:equals].strip()
        if equals == 0 or not attname:
            raise NameValueError(
                  'missing attribute name before "="')
        line = line[equals+1:].lstrip()
        if not line:
            raise NameValueError(
                  'missing value after "%s="' % attname)
        if line[0] in '\'"':
            endquote = line.find(line[0], 1)
            if endquote == -1:
                raise NameValueError(
                      'attribute "%s" missing end quote (%s)'
                      % (attname, line[0]))
            if len(line) > endquote + 1 and line[endquote + 1].strip():
                raise NameValueError(
                      'attribute "%s" end quote (%s) not followed by '
                      'whitespace' % (attname, line[0]))
            data = line[1:endquote]
            line = line[endquote+1:].lstrip()
        else:
            space = line.find(' ')
            if space == -1:
                data = line
                line = ''
            else:
                data = line[:space]
                line = line[space+1:].lstrip()
        attlist.append((attname.lower(), data))
    return attlist 
Example 42
Project: LMS   Author: RRZE-HPC   File: influxdbHandlerNative.py    (license) View Source Project 4 votes vote down vote up
def loggedin_users(blacklist):
    systemusers = blacklist
    users = []
    f = open("/etc/passwd")
    finput = f.read().strip()
    f.close()
    for line in finput.split("\n"):
        if re.match("^\s*$", line): continue
        linelist = re.split(":", line)
        if linelist[1] == "x":
            if len(linelist[0]) <= 8:
                systemusers.append(linelist[0])
            else:
                systemusers.append(linelist[0])
                systemusers.append(linelist[0][:7]+"+")
        else:
            uid = None
            try:
                uid = int(linelist[2])
                if uid < 1024:
                    if len(linelist[0]) <= 8:
                        systemusers.append(linelist[0])
                    else:
                        systemusers.append(linelist[0])
                        systemusers.append(linelist[0][:7]+"+")
            except:
                pass
    cmd = ["ps -ef"]
    try:
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        (out, err) = p.communicate()
    except subprocess.CalledProcessError, e:
        return -1
    if p.returncode:
        return -1
    if not out:
        return -1
    if err:
        return -1
    for line in out.split('\n'):
        if line.startswith("UID"): continue
        linelist = re.split("\s+", line)
        if linelist[0] != "" and linelist[0] not in systemusers and not re.match("\d+", linelist[0]):
            users.append(linelist[0])
    return len(set(users)) 
Example 43
Project: qgis-compactness   Author: gerrymandr   File: compactness_calculator.py    (license) View Source Project 4 votes vote down vote up
def generate_layer(self, layer=True, path=None):
        """Creates an in-memory layer and displays/saves it."""
        # Create a new layer in memory
        new_layer = QgsVectorLayer('Polygon', "compactness_scores", "memory")
        provider = new_layer.dataProvider()

        # Add the new fields
        new_fields = sorted(self.scores.keys())  # need the same order every time
        fields = self.features[0].fields()  # QgsFields object
        for field in new_fields:
            fields.append(QgsField(field, QVariant.Double, '', 20, 4))

        # All changes to the layer happen below
        new_layer.startEditing()

        # Set layer CRS
        # NOTE A warning message will still appear in QGIS
        # because this isn't set at layer creation time.
        new_layer.setCrs(self.crs)

        # Set layer attributes (fields)
        provider.addAttributes(fields.toList())
        new_layer.updateFields()

        # Update features with new data
        for i in xrange(0, len(self.features)):
            attributes = self.features[i].attributes()  # list of values
            for field in new_fields:
                attributes.append(float(self.scores[field][i]))
            self.features[i].setAttributes(attributes)

        # Add features
        provider.addFeatures(self.features)

        new_layer.commitChanges()
        new_layer.updateExtents()

        if path.strip() != "":
            if path.endswith(".json") or path.endswith(".geojson"):
                filetype = 'GeoJson'
            elif path.endswith(".shp"):
                filetype = 'ESRI Shapefile'
            else:
                QMessageBox.critical(self.dlg,
                                     'Error',
                                     u"Unsupported file type. Only GeoJSON (.json, .geojson) and ESRI Shapefile (.shp) are supported.")
                return False

            QgsVectorFileWriter.writeAsVectorFormat(new_layer,
                                                    path,
                                                    'utf-8',
                                                    new_layer.crs(),
                                                    filetype)
            print "Saved to " + path

        if layer:
            QgsMapLayerRegistry.instance().addMapLayer(new_layer)

        return True 
Example 44
Project: blackmamba   Author: zrzka   File: __init__.py    (license) View Source Project 4 votes vote down vote up
def extract_name_value(line):
    """
    Return a list of (name, value) from a line of the form "name=value ...".

    :Exception:
        `NameValueError` for invalid input (missing name, missing data, bad
        quotes, etc.).
    """
    attlist = []
    while line:
        equals = line.find('=')
        if equals == -1:
            raise NameValueError('missing "="')
        attname = line[:equals].strip()
        if equals == 0 or not attname:
            raise NameValueError(
                  'missing attribute name before "="')
        line = line[equals+1:].lstrip()
        if not line:
            raise NameValueError(
                  'missing value after "%s="' % attname)
        if line[0] in '\'"':
            endquote = line.find(line[0], 1)
            if endquote == -1:
                raise NameValueError(
                      'attribute "%s" missing end quote (%s)'
                      % (attname, line[0]))
            if len(line) > endquote + 1 and line[endquote + 1].strip():
                raise NameValueError(
                      'attribute "%s" end quote (%s) not followed by '
                      'whitespace' % (attname, line[0]))
            data = line[1:endquote]
            line = line[endquote+1:].lstrip()
        else:
            space = line.find(' ')
            if space == -1:
                data = line
                line = ''
            else:
                data = line[:space]
                line = line[space+1:].lstrip()
        attlist.append((attname.lower(), data))
    return attlist 
Example 45
Project: RST-vscode   Author: tht13   File: __init__.py    (license) View Source Project 4 votes vote down vote up
def extract_name_value(line):
    """
    Return a list of (name, value) from a line of the form "name=value ...".

    :Exception:
        `NameValueError` for invalid input (missing name, missing data, bad
        quotes, etc.).
    """
    attlist = []
    while line:
        equals = line.find('=')
        if equals == -1:
            raise NameValueError('missing "="')
        attname = line[:equals].strip()
        if equals == 0 or not attname:
            raise NameValueError(
                  'missing attribute name before "="')
        line = line[equals+1:].lstrip()
        if not line:
            raise NameValueError(
                  'missing value after "%s="' % attname)
        if line[0] in '\'"':
            endquote = line.find(line[0], 1)
            if endquote == -1:
                raise NameValueError(
                      'attribute "%s" missing end quote (%s)'
                      % (attname, line[0]))
            if len(line) > endquote + 1 and line[endquote + 1].strip():
                raise NameValueError(
                      'attribute "%s" end quote (%s) not followed by '
                      'whitespace' % (attname, line[0]))
            data = line[1:endquote]
            line = line[endquote+1:].lstrip()
        else:
            space = line.find(' ')
            if space == -1:
                data = line
                line = ''
            else:
                data = line[:space]
                line = line[space+1:].lstrip()
        attlist.append((attname.lower(), data))
    return attlist 
Example 46
Project: tf_aws_ecs_instance_draining_on_scale_in   Author: terraform-community-modules   File: __init__.py    (license) View Source Project 4 votes vote down vote up
def extract_name_value(line):
    """
    Return a list of (name, value) from a line of the form "name=value ...".

    :Exception:
        `NameValueError` for invalid input (missing name, missing data, bad
        quotes, etc.).
    """
    attlist = []
    while line:
        equals = line.find('=')
        if equals == -1:
            raise NameValueError('missing "="')
        attname = line[:equals].strip()
        if equals == 0 or not attname:
            raise NameValueError(
                  'missing attribute name before "="')
        line = line[equals+1:].lstrip()
        if not line:
            raise NameValueError(
                  'missing value after "%s="' % attname)
        if line[0] in '\'"':
            endquote = line.find(line[0], 1)
            if endquote == -1:
                raise NameValueError(
                      'attribute "%s" missing end quote (%s)'
                      % (attname, line[0]))
            if len(line) > endquote + 1 and line[endquote + 1].strip():
                raise NameValueError(
                      'attribute "%s" end quote (%s) not followed by '
                      'whitespace' % (attname, line[0]))
            data = line[1:endquote]
            line = line[endquote+1:].lstrip()
        else:
            space = line.find(' ')
            if space == -1:
                data = line
                line = ''
            else:
                data = line[:space]
                line = line[space+1:].lstrip()
        attlist.append((attname.lower(), data))
    return attlist