Python string.rstrip() Examples

The following are 30 code examples of string.rstrip(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module string , or try the search function .
Example #1
Source File: latex.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def visitNode_a_listing(self, node):
        fileName = os.path.join(self.currDir, node.getAttribute('href'))
        self.writer('\\begin{verbatim}\n')
        lines = map(string.rstrip, open(fileName).readlines())
        skipLines = int(node.getAttribute('skipLines') or 0)
        lines = lines[skipLines:]
        self.writer(text.removeLeadingTrailingBlanks('\n'.join(lines)))
        self.writer('\\end{verbatim}')

        # Write a caption for this source listing
        fileName = os.path.basename(fileName)
        caption = domhelpers.getNodeText(node)
        if caption == fileName:
            caption = 'Source listing'
        self.writer('\parbox[b]{\linewidth}{\\begin{center}%s --- '
                    '\\begin{em}%s\\end{em}\\end{center}}'
                    % (latexEscape(caption), latexEscape(fileName))) 
Example #2
Source File: latex.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def visitNode_a_listing(self, node):
        fileName = os.path.join(self.currDir, node.getAttribute('href'))
        self.writer('\\begin{verbatim}\n')
        lines = map(string.rstrip, open(fileName).readlines())
        lines = lines[int(node.getAttribute('skipLines', 0)):]
        self.writer(text.removeLeadingTrailingBlanks('\n'.join(lines)))
        self.writer('\\end{verbatim}')

        # Write a caption for this source listing
        fileName = os.path.basename(fileName)
        caption = domhelpers.getNodeText(node)
        if caption == fileName:
            caption = 'Source listing'
        self.writer('\parbox[b]{\linewidth}{\\begin{center}%s --- '
                    '\\begin{em}%s\\end{em}\\end{center}}'
                    % (latexEscape(caption), latexEscape(fileName))) 
Example #3
Source File: pythondoc.py    From InternationalizationScript-iOS with MIT License 6 votes vote down vote up
def look_for_pythondoc(self, type, token, start, end, line):
        if type == tokenize.COMMENT and string.rstrip(token) == "##":
            # found a comment: set things up for comment processing
            self.comment_start = start
            self.comment = []
            return self.process_comment_body
        else:
            # deal with "bare" subjects
            if token == "def" or token == "class":
                self.subject_indent = self.indent
                self.subject_parens = 0
                self.subject_start = self.comment_start = None
                self.subject = []
                return self.process_subject(type, token, start, end, line)
            return self.look_for_pythondoc

    ##
    # (Token handler) Processes a comment body.  This handler adds
    # comment lines to the current comment. 
Example #4
Source File: sqlifinderb0t.py    From d4rkc0de with GNU General Public License v2.0 6 votes vote down vote up
def getsites(lang):
	try:
                page_counter=0
    		while page_counter < int(arg_page_end):
                        s.send("PONG %s\r\n" % line[1]) 
			time.sleep(3)
                        results_web = 'http://www.google.com/search?q='+str(query)+'&hl='+str(lang)+'&lr=&ie=UTF-8&start='+repr(page_counter)+'&sa=N'
        		request_web = urllib2.Request(results_web)
        		request_web.add_header('User-Agent',random.choice(agents))
        		opener_web = urllib2.build_opener()
        		text = opener_web.open(request_web).read()
                        if re.search("403 Forbidden", text):
                                s.send("PRIVMSG %s :%s\r\n" % (CHAN, "[-] Received Captcha... Damn that sucks!"))
                                break
        		names = re.findall(('<cite>+[\w\d\?\/\.\=\s\-]+=+[\d]+[\w\d\?\/\.\=\s\-]+</cite>'),text.replace("<b>","").replace("</b>",""))
        		for name in names:
				name = re.sub(" - \d+k - </cite>","",name.replace("<cite>","")).replace("</cite>","")
				name = name.rstrip(" -")
				sites.append(name)
        		page_counter +=10
                                
	except IOError:
		s.send("PRIVMSG %s :%s\r\n" % (CHAN, "[-] Can't connect to Google Web!")) 
Example #5
Source File: sqlifinderb0t.py    From darkc0de-old-stuff with GNU General Public License v3.0 6 votes vote down vote up
def getsites(lang):
	try:
                page_counter=0
    		while page_counter < int(arg_page_end):
                        s.send("PONG %s\r\n" % line[1]) 
			time.sleep(3)
                        results_web = 'http://www.google.com/search?q='+str(query)+'&hl='+str(lang)+'&lr=&ie=UTF-8&start='+repr(page_counter)+'&sa=N'
        		request_web = urllib2.Request(results_web)
        		request_web.add_header('User-Agent',random.choice(agents))
        		opener_web = urllib2.build_opener()
        		text = opener_web.open(request_web).read()
                        if re.search("403 Forbidden", text):
                                s.send("PRIVMSG %s :%s\r\n" % (CHAN, "[-] Received Captcha... Damn that sucks!"))
                                break
        		names = re.findall(('<cite>+[\w\d\?\/\.\=\s\-]+=+[\d]+[\w\d\?\/\.\=\s\-]+</cite>'),text.replace("<b>","").replace("</b>",""))
        		for name in names:
				name = re.sub(" - \d+k - </cite>","",name.replace("<cite>","")).replace("</cite>","")
				name = name.rstrip(" -")
				sites.append(name)
        		page_counter +=10
                                
	except IOError:
		s.send("PRIVMSG %s :%s\r\n" % (CHAN, "[-] Can't connect to Google Web!")) 
Example #6
Source File: pythondoc.py    From InternationalizationScript-iOS with MIT License 6 votes vote down vote up
def look_for_pythondoc(self, type, token, start, end, line):
        if type == tokenize.COMMENT and string.rstrip(token) == "##":
            # found a comment: set things up for comment processing
            self.comment_start = start
            self.comment = []
            return self.process_comment_body
        else:
            # deal with "bare" subjects
            if token == "def" or token == "class":
                self.subject_indent = self.indent
                self.subject_parens = 0
                self.subject_start = self.comment_start = None
                self.subject = []
                return self.process_subject(type, token, start, end, line)
            return self.look_for_pythondoc

    ##
    # (Token handler) Processes a comment body.  This handler adds
    # comment lines to the current comment. 
Example #7
Source File: pydoc.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def section(self, title, contents):
        """Format a section with a given heading."""
        return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'

    # ---------------------------------------------- type-specific routines 
Example #8
Source File: pydoc.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def getdoc(object):
    """Get the doc string or comments for an object."""
    result = inspect.getdoc(object) or inspect.getcomments(object)
    return result and re.sub('^ *\n', '', rstrip(result)) or '' 
Example #9
Source File: pydoc.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def getdoc(object):
    """Get the doc string or comments for an object."""
    result = inspect.getdoc(object) or inspect.getcomments(object)
    return result and re.sub('^ *\n', '', rstrip(result)) or '' 
Example #10
Source File: pydoc.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def getdoc(object):
    """Get the doc string or comments for an object."""
    result = inspect.getdoc(object) or inspect.getcomments(object)
    result = _encode(result)
    return result and re.sub('^ *\n', '', rstrip(result)) or '' 
Example #11
Source File: mypydoc.py    From azure-linux-extensions with Apache License 2.0 5 votes vote down vote up
def splitdoc(doc):
    """Split a doc string into a synopsis line (if any) and the rest."""
    lines = split(strip(doc), '\n')
    if len(lines) == 1:
        return lines[0], ''
    elif len(lines) >= 2 and not rstrip(lines[1]):
        return lines[0], join(lines[2:], '\n')
    return '', join(lines, '\n') 
Example #12
Source File: mypydoc.py    From azure-linux-extensions with Apache License 2.0 5 votes vote down vote up
def getdocloc(self, object):
        """Return the location of module docs or None"""

        try:
            file = inspect.getabsfile(object)
        except TypeError:
            file = '(built-in)'

        docloc = os.environ.get("PYTHONDOCS",
                                "http://docs.python.org/library")
        basedir = os.path.join(sys.exec_prefix, "lib",
                               "python"+sys.version[0:3])
        if (isinstance(object, type(os)) and
            (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
                                 'marshal', 'posix', 'signal', 'sys',
                                 'thread', 'zipimport') or
             (file.startswith(basedir) and
              not file.startswith(os.path.join(basedir, 'dist-packages')) and
              not file.startswith(os.path.join(basedir, 'site-packages')))) and
            object.__name__ not in ('xml.etree', 'test.pydoc_mod')):
            if docloc.startswith("http://"):
                docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__)
            else:
                docloc = os.path.join(docloc, object.__name__ + ".html")
        else:
            docloc = None
        return docloc

# -------------------------------------------- HTML documentation generator 
Example #13
Source File: mypydoc.py    From azure-linux-extensions with Apache License 2.0 5 votes vote down vote up
def indent(self, text, prefix='    '):
        """Indent text by prepending a given prefix to each line."""
        if not text: return ''
        lines = split(text, '\n')
        lines = map(lambda line, prefix=prefix: prefix + line, lines)
        if lines: lines[-1] = rstrip(lines[-1])
        return join(lines, '\n') 
Example #14
Source File: mypydoc.py    From azure-linux-extensions with Apache License 2.0 5 votes vote down vote up
def section(self, title, contents):
        """Format a section with a given heading."""
        return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'

    # ---------------------------------------------- type-specific routines 
Example #15
Source File: pydoc.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def getdocloc(self, object):
        """Return the location of module docs or None"""

        try:
            file = inspect.getabsfile(object)
        except TypeError:
            file = '(built-in)'

        docloc = os.environ.get("PYTHONDOCS",
                                "http://docs.python.org/library")
        basedir = os.path.join(sys.exec_prefix, "lib",
                               "python"+sys.version[0:3])
        if (isinstance(object, type(os)) and
            (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
                                 'marshal', 'posix', 'signal', 'sys',
                                 'thread', 'zipimport') or
             (file.startswith(basedir) and
              not file.startswith(os.path.join(basedir, 'site-packages')))) and
            object.__name__ not in ('xml.etree', 'test.pydoc_mod')):
            if docloc.startswith("http://"):
                docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__)
            else:
                docloc = os.path.join(docloc, object.__name__ + ".html")
        else:
            docloc = None
        return docloc

# -------------------------------------------- HTML documentation generator 
Example #16
Source File: pydoc.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def section(self, title, contents):
        """Format a section with a given heading."""
        return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'

    # ---------------------------------------------- type-specific routines 
Example #17
Source File: pydoc.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def indent(self, text, prefix='    '):
        """Indent text by prepending a given prefix to each line."""
        if not text: return ''
        lines = split(text, '\n')
        lines = map(lambda line, prefix=prefix: prefix + line, lines)
        if lines: lines[-1] = rstrip(lines[-1])
        return join(lines, '\n') 
Example #18
Source File: mypydoc.py    From azure-linux-extensions with Apache License 2.0 5 votes vote down vote up
def getdoc(object):
    """Get the doc string or comments for an object."""
    result = inspect.getdoc(object) or inspect.getcomments(object)
    return result and re.sub('^ *\n', '', rstrip(result)) or '' 
Example #19
Source File: pydoc.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def indent(self, text, prefix='    '):
        """Indent text by prepending a given prefix to each line."""
        if not text: return ''
        lines = split(text, '\n')
        lines = map(lambda line, prefix=prefix: prefix + line, lines)
        if lines: lines[-1] = rstrip(lines[-1])
        return join(lines, '\n') 
Example #20
Source File: pydoc.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def getdocloc(self, object):
        """Return the location of module docs or None"""

        try:
            file = inspect.getabsfile(object)
        except TypeError:
            file = '(built-in)'

        docloc = os.environ.get("PYTHONDOCS",
                                "http://docs.python.org/library")
        basedir = os.path.join(sys.exec_prefix, "lib",
                               "python"+sys.version[0:3])
        if (isinstance(object, type(os)) and
            (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
                                 'marshal', 'posix', 'signal', 'sys',
                                 'thread', 'zipimport') or
             (file.startswith(basedir) and
              not file.startswith(os.path.join(basedir, 'site-packages')))) and
            object.__name__ not in ('xml.etree', 'test.pydoc_mod')):
            if docloc.startswith("http://"):
                docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__)
            else:
                docloc = os.path.join(docloc, object.__name__ + ".html")
        else:
            docloc = None
        return docloc

# -------------------------------------------- HTML documentation generator 
Example #21
Source File: pydoc.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def splitdoc(doc):
    """Split a doc string into a synopsis line (if any) and the rest."""
    lines = split(strip(doc), '\n')
    if len(lines) == 1:
        return lines[0], ''
    elif len(lines) >= 2 and not rstrip(lines[1]):
        return lines[0], join(lines[2:], '\n')
    return '', join(lines, '\n') 
Example #22
Source File: pydoc.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def splitdoc(doc):
    """Split a doc string into a synopsis line (if any) and the rest."""
    lines = split(strip(doc), '\n')
    if len(lines) == 1:
        return lines[0], ''
    elif len(lines) >= 2 and not rstrip(lines[1]):
        return lines[0], join(lines[2:], '\n')
    return '', join(lines, '\n') 
Example #23
Source File: tree.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def addPyListings(document, dir):
    for node in domhelpers.findElementsWithAttribute(document, "class",
                                                     "py-listing"):
        filename = node.getAttribute("href")
        outfile = cStringIO.StringIO()
        lines = map(string.rstrip, open(os.path.join(dir, filename)).readlines())
        data = '\n'.join(lines[int(node.getAttribute('skipLines', 0)):])
        data = cStringIO.StringIO(text.removeLeadingTrailingBlanks(data))
        htmlizer.filter(data, outfile, writer=htmlizer.SmallerHTMLWriter)
        val = outfile.getvalue()
        _replaceWithListing(node, val, filename, "py-listing") 
Example #24
Source File: util.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def htmlIndent(snippetLine):
    ret = string.replace(string.replace(html.escape(string.rstrip(snippetLine)),
                                  '  ', '&nbsp;'),
                   '\t', '&nbsp; &nbsp; &nbsp; &nbsp; ')
    return ret 
Example #25
Source File: pydoc.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def section(self, title, contents):
        """Format a section with a given heading."""
        return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'

    # ---------------------------------------------- type-specific routines 
Example #26
Source File: pydoc.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def indent(self, text, prefix='    '):
        """Indent text by prepending a given prefix to each line."""
        if not text: return ''
        lines = split(text, '\n')
        lines = map(lambda line, prefix=prefix: prefix + line, lines)
        if lines: lines[-1] = rstrip(lines[-1])
        return join(lines, '\n') 
Example #27
Source File: pydoc.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def getdocloc(self, object):
        """Return the location of module docs or None"""

        try:
            file = inspect.getabsfile(object)
        except TypeError:
            file = '(built-in)'

        docloc = os.environ.get("PYTHONDOCS",
                                "http://www.python.org/doc/current/lib")
        basedir = os.path.join(sys.exec_prefix, "lib",
                               "python"+sys.version[0:3])
        if (isinstance(object, type(os)) and
            (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
                                 'marshal', 'posix', 'signal', 'sys',
                                 'thread', 'zipimport') or
             (file.startswith(basedir) and
              not file.startswith(os.path.join(basedir, 'site-packages'))))):
            htmlfile = "module-%s.html" % object.__name__
            if docloc.startswith("http://"):
                docloc = "%s/%s" % (docloc.rstrip("/"), htmlfile)
            else:
                docloc = os.path.join(docloc, htmlfile)
        else:
            docloc = None
        return docloc

# -------------------------------------------- HTML documentation generator 
Example #28
Source File: pydoc.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def splitdoc(doc):
    """Split a doc string into a synopsis line (if any) and the rest."""
    lines = split(strip(doc), '\n')
    if len(lines) == 1:
        return lines[0], ''
    elif len(lines) >= 2 and not rstrip(lines[1]):
        return lines[0], join(lines[2:], '\n')
    return '', join(lines, '\n') 
Example #29
Source File: pydoc.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def getdoc(object):
    """Get the doc string or comments for an object."""
    result = inspect.getdoc(object) or inspect.getcomments(object)
    return result and re.sub('^ *\n', '', rstrip(result)) or '' 
Example #30
Source File: tree.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def addPyListings(document, dir):
    """
    Insert Python source listings into the given document from files in the
    given directory based on C{py-listing} nodes.

    Any node in C{document} with a C{class} attribute set to C{py-listing} will
    have source lines taken from the file named in that node's C{href}
    attribute (searched for in C{dir}) inserted in place of that node.

    If a node has a C{skipLines} attribute, its value will be parsed as an
    integer and that many lines will be skipped at the beginning of the source
    file.

    @type document: A DOM Node or Document
    @param document: The document within which to make listing replacements.

    @type dir: C{str}
    @param dir: The directory in which to find source files containing the
    referenced Python listings.

    @return: C{None}
    """
    for node in domhelpers.findElementsWithAttribute(document, "class",
                                                     "py-listing"):
        filename = node.getAttribute("href")
        outfile = cStringIO.StringIO()
        lines = map(string.rstrip, open(os.path.join(dir, filename)).readlines())

        skip = node.getAttribute('skipLines') or 0
        lines = lines[int(skip):]
        howManyLines = len(lines)
        data = '\n'.join(lines)

        data = cStringIO.StringIO(text.removeLeadingTrailingBlanks(data))
        htmlizer.filter(data, outfile, writer=htmlizer.SmallerHTMLWriter)
        sourceNode = dom.parseString(outfile.getvalue()).documentElement
        sourceNode.insertBefore(_makeLineNumbers(howManyLines), sourceNode.firstChild)
        _replaceWithListing(node, sourceNode.toxml(), filename, "py-listing")