當前位置: 首頁>>代碼示例>>Python>>正文


Python string.printable方法代碼示例

本文整理匯總了Python中string.printable方法的典型用法代碼示例。如果您正苦於以下問題:Python string.printable方法的具體用法?Python string.printable怎麽用?Python string.printable使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在string的用法示例。


在下文中一共展示了string.printable方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_sample_info

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def get_sample_info(vt_rep, from_vt):
        '''Parse and extract sample information from JSON line
           Returns a SampleInfo named tuple: md5, sha1, sha256, label_pairs 
        '''
        label_pairs = []
        if from_vt:
            try:
                scans = vt_rep['scans']
            except KeyError:
                return None
            for av, res in scans.items():
                if res['detected']:
                    label = res['result']
                    clean_label = filter(lambda x: x in string.printable,
                                         label).strip().encode('utf-8').strip()
                    label_pairs.append((av, clean_label))
        else:
            label_pairs = vt_rep['av_labels']

        return SampleInfo(vt_rep['md5'], vt_rep['sha1'], vt_rep['sha256'],
                          label_pairs) 
開發者ID:Cisco-Talos,項目名稱:BASS,代碼行數:23,代碼來源:avclass_common.py

示例2: _search_validator

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def _search_validator(self, ch):
        """Fix Enter and backspace for textbox.

        Used as an aux function for the textpad.edit method

        """
        if ch == curses.ascii.NL:  # Enter
            return curses.ascii.BEL
        elif ch == 127:  # Backspace
            self.search_str = self.textpad.gather().strip().lower()[:-1]
            return 8
        else:
            if 0 < ch < 256:
                c = chr(ch)
                if c in string.printable:
                    res = self.textpad.gather().strip().lower()
                    self.search_str = res + chr(ch)
                    self.search_results(look_in_cur=True)
                    self.display()
            return ch 
開發者ID:OpenTrading,項目名稱:OpenTrader,代碼行數:22,代碼來源:tabview.py

示例3: encode

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def encode(self, data):
        length = len(data)

        if not self.is_in_range(length):
            raise ConstraintsError(
                'Expected between {} and {} characters, but got {}.'.format(
                    self.minimum,
                    self.maximum,
                    length))

        if self.permitted_alphabet is None:
            return

        for character in data:
            if character not in self.permitted_alphabet:
                raise ConstraintsError(
                    "Expected a character in '{}', but got '{}' (0x{:02x}).".format(
                        ''.join([c if c in string.printable[:-5] else '.'
                                 for c in self.permitted_alphabet]),
                        character if character in string.printable else '.',
                        ord(character))) 
開發者ID:eerimoq,項目名稱:asn1tools,代碼行數:23,代碼來源:constraints_checker.py

示例4: anything_beetween

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def anything_beetween(opener_and_closer):
    """Builds a (pyparsing) parser for the content inside delimiters.

    Args:
    opener_and_closer: a string containing two elements: opener and closer

    Returns:
      A (pyparsing) parser for the content inside delimiters.
    """
    opener = pyparsing.Literal(opener_and_closer[0])
    closer = pyparsing.Literal(opener_and_closer[1])
    char_removal_mapping = dict.fromkeys(map(ord, opener_and_closer))
    other_chars = unicode(string.printable).translate(char_removal_mapping)
    word_without_delimiters = pyparsing.Word(other_chars).setName(
        "other_chars")
    anything = pyparsing.Forward()
    delimited_block = opener + anything + closer
    # pylint: disable=expression-not-assigned
    anything << pyparsing.ZeroOrMore(
        word_without_delimiters.setName("word_without_delimiters")
        | delimited_block.setName("delimited_block")
    )

    # Combine all the parts into a single string.
    return pyparsing.Combine(anything) 
開發者ID:google,項目名稱:rekall,代碼行數:27,代碼來源:parsers.py

示例5: anything_beetween

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def anything_beetween(opener_and_closer):
    """Builds a (pyparsing) parser for the content inside delimiters.

    Args:
    opener_and_closer: a string containing two elements: opener and closer

    Returns:
      A (pyparsing) parser for the content inside delimiters.
    """
    opener = pyparsing.Literal(opener_and_closer[0])
    closer = pyparsing.Literal(opener_and_closer[1])
    char_removal_mapping = dict.fromkeys(list(map(ord, opener_and_closer)))
    other_chars = str(string.printable).translate(char_removal_mapping)
    word_without_delimiters = pyparsing.Word(other_chars).setName(
        "other_chars")
    anything = pyparsing.Forward()
    delimited_block = opener + anything + closer
    # pylint: disable=expression-not-assigned
    anything << pyparsing.ZeroOrMore(
        word_without_delimiters.setName("word_without_delimiters")
        | delimited_block.setName("delimited_block")
    )

    # Combine all the parts into a single string.
    return pyparsing.Combine(anything) 
開發者ID:google,項目名稱:rekall,代碼行數:27,代碼來源:yara_support.py

示例6: nextGlobalString

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def nextGlobalString(self, ea):
        """Find the next possible address for a global string, given the beginning of the current global string.

        Args:
            ea (int): effective start address of the current global string.

        Return Value:
            Possible start address for the next global string
        """
        str_content = self.getAsciiString(ea)
        if str_content is None:
            return ea + self._global_alignment
        elif idc.get_wide_byte(ea + len(str_content)) != ord('\0'):
            return ea + max(self._global_alignment, pad(len(str_content), self._global_alignment))
        else:
            for offset in range(len(str_content) - 1, -1, -1):
                if chr(str_content[offset]) not in string.printable:
                    return ea + max(self._global_alignment, pad(offset, self._global_alignment))
        return ea + self._global_alignment 
開發者ID:CheckPointSW,項目名稱:Karta,代碼行數:21,代碼來源:strings.py

示例7: check_yara

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def check_yara(self, data):
        ret = []
        if self.rules:
            yarahits = self.rules.match(data=data)
            if yarahits:
              for hit in yarahits:
                ret.append("YARA: %s" % hit.rule)
                #for key, val in hit.strings.iteritems():
                for (key,stringname,val) in hit.strings:
                    makehex = False
                    for char in val:
                        if char not in string.printable:
                            makehex = True
                            break
                    if makehex == True:
                        ret.append("   %s => %s" % (hex(key), binascii.hexlify(val)))
                    else:
                        ret.append("   %s => %s" % (hex(key), val))
        return '\n'.join(ret) 
開發者ID:omriher,項目名稱:CapTipper,代碼行數:21,代碼來源:pescanner.py

示例8: handle_string

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def handle_string(self, token_text):
        if self.last_type in ['TK_START_BLOCK', 'TK_END_BLOCK', 'TK_SEMICOLON']:
            self.append_newline()
        elif self.last_type == 'TK_WORD':
            self.append(' ')

        # Try to replace readable \x-encoded characters with their equivalent,
        # if it is possible (e.g. '\x41\x42\x43\x01' becomes 'ABC\x01').
        def unescape(match):
            block, code = match.group(0, 1)
            char = chr(int(code, 16))
            if block.count('\\') == 1 and char in string.printable:
                return char
            return block

        token_text = re.sub(r'\\{1,2}x([a-fA-F0-9]{2})', unescape, token_text)

        self.append(token_text) 
開發者ID:omriher,項目名稱:CapTipper,代碼行數:20,代碼來源:__init__.py

示例9: filter_characters

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def filter_characters(self, allow_chars=string.printable, drop_chars=None):
        """
        Filter the document strings by removing all characters but those in `allow_chars` or, if `allow_chars` evaluates
        to False, remove those in `drop_chars`.

        :param allow_chars: set (like ``{'a', 'b', 'c'}`` or string sequence (like ``'abc'``)
        :param drop_chars: set or string sequence of characters to remove (if `allow_chars` evaluates to False)
        :return: this instance
        """

        if allow_chars is not None:
            if not isinstance(allow_chars, set):
                allow_chars = set(allow_chars)

            drop_chars = ''.join(self.unique_characters - allow_chars)
        else:
            if isinstance(drop_chars, (set, list, tuple)):
                drop_chars = ''.join(drop_chars)

            if not isinstance(drop_chars, str):
                raise ValueError('`drop_chars` must be a sequence, set or string if `allow_chars` is not given')

        return self.replace_characters(str.maketrans(drop_chars, drop_chars, drop_chars)) 
開發者ID:WZBSocialScienceCenter,項目名稱:tmtoolkit,代碼行數:25,代碼來源:corpus.py

示例10: _restart_qemu

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def _restart_qemu(self):
    """Restart QEMU."""
    logs.log_warn(
        'Connection to fuzzing VM lost. Restarting.',
        processes=process_handler.get_runtime_snapshot())
    stop_qemu()

    # Do this after the stop, to make sure everything is flushed
    if os.path.exists(QemuProcess.LOG_PATH):
      with open(QemuProcess.LOG_PATH) as f:
        # Strip non-printable characters at beginning of qemu log
        qemu_log = ''.join(c for c in f.read() if c in string.printable)
        logs.log_warn(qemu_log)
    else:
      logs.log_error('Qemu log not found in {}'.format(QemuProcess.LOG_PATH))

    start_qemu()
    self._setup_device_and_fuzzer() 
開發者ID:google,項目名稱:clusterfuzz,代碼行數:20,代碼來源:libfuzzer.py

示例11: test_enabling_brick_mux_with_wrong_values

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def test_enabling_brick_mux_with_wrong_values(self):
        """
        Test Case:
        - Create a gluster cluster
        - Set cluster.brick-multiplex value to random string(Must fail)
        - Set cluster.brick-multiplex value to random int(Must fail)
        - Set cluster.brick-multiplex value to random
          special characters(Must fail)
        """
        # Creation of random data for cluster.brick-multiplex option
        # Data has: alphabets, numbers, punctuations and their combinations
        key = 'cluster.brick-multiplex'
        for char_type in (string.ascii_letters, string.punctuation,
                          string.printable, string.digits):

            temp_val = self.get_random_string(char_type)
            value = "{}".format(temp_val)
            ret = set_volume_options(self.mnode, 'all', {key: value})
            self.assertFalse(ret, "Unexpected: Erroneous value {}, to option "
                             "{} should result in failure".format(value, key))
            g.log.info("Expected: Erroneous value %s, to option "
                       "%s resulted in failure", value, key) 
開發者ID:gluster,項目名稱:glusto-tests,代碼行數:24,代碼來源:test_enabling_brick_mux.py

示例12: format

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def format(self, record):
        try:
            message = super(SecureFormatter, self).format(record)
        except TypeError:
            # In pyhton 2.6 the Formatter does not seem to 
            # be defined as 
            # class Formatter(object)
            # Using it in the super-statement this will raise a TypeError
            message = Formatter.format(self, record)
        secured = False

        s = ""
        for c in message:
            if c in string.printable:
                s += c
            else:
                s += '.'
                secured = True

        if secured:
            s = "!!!Log Entry Secured by SecureFormatter!!! " + s

        return s 
開發者ID:privacyidea,項目名稱:privacyidea,代碼行數:25,代碼來源:log.py

示例13: convert_arg_line_to_args

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def convert_arg_line_to_args(self, line):
        # Strip any non-printable characters that might be in the
        # beginning of the line (e.g. Unicode BOM marker).
        match = _printable_re.search(line)
        if not match:
            return
        line = line[match.start():].strip()

        # Skip lines that do not start with a valid option (e.g. comments)
        option = _option_re.match(line)
        if not option:
            return

        name, value = option.group("name", "value")
        if name and value:
            yield u"--{0}={1}".format(name, value)
        elif name:
            yield u"--{0}".format(name) 
開發者ID:streamlink,項目名稱:streamlink,代碼行數:20,代碼來源:argparser.py

示例14: _monitor_process

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def _monitor_process(proc, error_message):
        try:
            yield from proc.wait()
        except:
            proc.terminate()
            raise

        if proc.returncode:
            if proc.stderr is not None:
                proc_stderr = (yield from proc.stderr.read())
                proc_stderr = proc_stderr.decode('ascii', errors='ignore')
                proc_stderr = ''.join(
                    c for c in proc_stderr if c in string.printable and
                                              c not in '\r\n%{}')
                error_message += ': ' + proc_stderr
            raise qubes.exc.QubesException(error_message) 
開發者ID:QubesOS,項目名稱:qubes-core-admin,代碼行數:18,代碼來源:backup.py

示例15: __init__

# 需要導入模塊: import string [as 別名]
# 或者: from string import printable [as 別名]
def __init__(self, keys=None, buttonmasks=None, screen_shape=(1024, 728)):
        self.keys = []
        if keys is None:
            keys = [c for c in string.printable] + list(constants.KEYMAP.keys())
        for key in (keys or []):
            down = vnc_event.KeyEvent.by_name(key, down=True)
            up = vnc_event.KeyEvent.by_name(key, down=False)
            self.keys.append(down)
            self.keys.append(up)
        self._key_set = set(self.keys)

        self.screen_shape = screen_shape
        if self.screen_shape is not None:
            self.buttonmasks = []
            if buttonmasks is None:
                buttonmasks = range(256)
            for buttonmask in buttonmasks:
                self.buttonmasks.append(buttonmask)
            self._buttonmask_set = set(self.buttonmasks) 
開發者ID:openai,項目名稱:universe,代碼行數:21,代碼來源:vnc_action_space.py


注:本文中的string.printable方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。