本文整理汇总了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)
示例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
示例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)))
示例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)
示例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)
示例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
示例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)
示例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)
示例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))
示例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()
示例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)
示例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
示例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)
示例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)
示例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)