本文整理汇总了Python中uu.decode函数的典型用法代码示例。如果您正苦于以下问题:Python decode函数的具体用法?Python decode怎么用?Python decode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了decode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: decode_payload
def decode_payload(self, encoding, payload):
"""
Decode attachment payload data.
:param encoding:
The current encoding of the payload data.
:param payload:
the payload data
"""
cte = encoding.lower()
if cte == 'quoted-printable':
return utils._qdecode(payload)
elif cte == 'base64':
try:
return utils._bdecode(payload)
except binascii.Error:
# Incorrect padding
return payload
elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
sfp = StringIO()
try:
uu.decode(StringIO(payload + '\n'), sfp, quiet=True)
payload = sfp.getvalue()
except uu.Error:
# Some decoding problem
return payload
示例2: invoke
def invoke(self, sessionID, service, method, *args):
# Raise exception if this is not a valid session
if not self.manager().validate(sessionID, touch=1):
raise EInvalidSession('Invalid session')
s = self._as_node(service)
a = getattr(s, method)
## Check to see if any of the args have been UUEncoded
## If so, decode them here..
cnt=-1
args_new = []
args_new.extend( args )
for ar in args_new:
cnt = cnt + 1
if type(ar) == types.StringType:
if ar.startswith('begin '): # is uuencoded
infile = StringIO.StringIO(ar)
outfile = StringIO.StringIO()
uu.decode(infile, outfile )
args_new[cnt] = outfile.getvalue()
result = apply(a, args_new)
if isinstance(result,BinaryString):
# This is the legacy ConfigTool specific base64 encoding.
return ''.join(("<encode type='base64'>",
base64.standard_b64encode(result),
"</encode>"))
return result
示例3: test_garbage_padding
def test_garbage_padding(self):
# Issue #22406
encodedtext1 = (
b"begin 644 file\n"
# length 1; bits 001100 111111 111111 111111
b"\x21\x2C\x5F\x5F\x5F\n"
b"\x20\n"
b"end\n"
)
encodedtext2 = (
b"begin 644 file\n"
# length 1; bits 001100 111111 111111 111111
b"\x21\x2C\x5F\x5F\x5F\n"
b"\x60\n"
b"end\n"
)
plaintext = b"\x33" # 00110011
for encodedtext in encodedtext1, encodedtext2:
with self.subTest("uu.decode()"):
inp = io.BytesIO(encodedtext)
out = io.BytesIO()
uu.decode(inp, out, quiet=True)
self.assertEqual(out.getvalue(), plaintext)
with self.subTest("uu_codec"):
import codecs
decoded = codecs.decode(encodedtext, "uu_codec")
self.assertEqual(decoded, plaintext)
示例4: block_dev_get_crypto_footer
def block_dev_get_crypto_footer(block_dev):
"""
Looks for a crypto footer at the end of a block device and returns the
footer object if there is one.
If there is not footer, False is returned.
If there were any errors, None is returned
"""
shortname = os.path.basename(block_dev)
print_progress('Checking if {} has a crypto footer... '.format(shortname))
size = block_dev_get_size_in_512_bytes(block_dev)
if not size: return
if size*512 < 16*1024:
print_error('Size of {} is just {} bytes.'.format(size*512))
return
# FIXME busybox seems to be compiled without large file support and fails
# to supply sane data at the end of partitions larger than 2 GiB.
skip = size - 16*1024/512
footer_text = adb_shell(('dd if={} bs=512 count=32 skip={} 2>/dev/null'
'| uuencode -')
.format(block_dev, skip))
footer_bytes = BytesIO()
uu.decode(BytesIO(footer_text), footer_bytes)
footer_bytes.seek(0)
try:
return cryptfooter.CryptFooter(footer_bytes)
except cryptfooter.ValidationException as e:
return False
示例5: test_missingbegin
def test_missingbegin(self):
inp = io.BytesIO(b"")
out = io.BytesIO()
try:
uu.decode(inp, out)
self.fail("No exception raised")
except uu.Error as e:
self.assertEqual(str(e), "No valid begin line found in input file")
示例6: test_truncatedinput
def test_truncatedinput(self):
inp = cStringIO.StringIO("begin 644 t1\n" + encodedtext)
out = cStringIO.StringIO()
try:
uu.decode(inp, out)
self.fail("No exception thrown")
except uu.Error, e:
self.assertEqual(str(e), "Truncated input file")
示例7: test_decode
def test_decode(self):
sys.stdin = FakeIO(encodedtextwrapped(0o666, "t1").decode("ascii"))
sys.stdout = FakeIO()
uu.decode("-", "-")
stdout = sys.stdout
sys.stdout = self.stdout
sys.stdin = self.stdin
self.assertEqual(stdout.getvalue(), plaintext.decode("ascii"))
示例8: test_truncatedinput
def test_truncatedinput(self):
inp = io.BytesIO(b"begin 644 t1\n" + encodedtext)
out = io.BytesIO()
try:
uu.decode(inp, out)
self.fail("No exception raised")
except uu.Error as e:
self.assertEqual(str(e), "Truncated input file")
示例9: test_missingbegin
def test_missingbegin(self):
inp = cStringIO.StringIO("")
out = cStringIO.StringIO()
try:
uu.decode(inp, out)
self.fail("No exception thrown")
except uu.Error, e:
self.assertEqual(str(e), "No valid begin line found in input file")
示例10: get_payload
def get_payload(self, i=None, decode=False):
"""Return a reference to the payload.
The payload will either be a list object or a string. If you mutate
the list object, you modify the message's payload in place. Optional
i returns that index into the payload.
Optional decode is a flag indicating whether the payload should be
decoded or not, according to the Content-Transfer-Encoding header
(default is False).
When True and the message is not a multipart, the payload will be
decoded if this header's value is `quoted-printable' or `base64'. If
some other encoding is used, or the header is missing, or if the
payload has bogus data (i.e. bogus base64 or uuencoded data), the
payload is returned as-is.
If the message is a multipart and the decode flag is True, then None
is returned.
"""
if i is None:
payload = self._payload
elif not isinstance(self._payload, list):
raise TypeError('Expected list, got %s' % type(self._payload))
else:
payload = self._payload[i]
if not decode:
return payload
# Decoded payloads always return bytes. XXX split this part out into
# a new method called .get_decoded_payload().
if self.is_multipart():
return None
cte = self.get('content-transfer-encoding', '').lower()
if cte == 'quoted-printable':
return utils._qdecode(payload)
elif cte == 'base64':
try:
if isinstance(payload, str):
payload = payload.encode('raw-unicode-escape')
return base64.b64decode(payload)
#return utils._bdecode(payload)
except binascii.Error:
# Incorrect padding
pass
elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
in_file = BytesIO(payload.encode('raw-unicode-escape'))
out_file = BytesIO()
try:
uu.decode(in_file, out_file, quiet=True)
return out_file.getvalue()
except uu.Error:
# Some decoding problem
pass
# Is there a better way to do this? We can't use the bytes
# constructor.
if isinstance(payload, str):
return payload.encode('raw-unicode-escape')
return payload
示例11: test_decodetwice
def test_decodetwice(self):
# Verify that decode() will refuse to overwrite an existing file
with open(self.tmpin, 'wb') as f:
f.write(encodedtextwrapped(0o644, self.tmpout))
with open(self.tmpin, 'rb') as f:
uu.decode(f)
with open(self.tmpin, 'rb') as f:
self.assertRaises(uu.Error, uu.decode, f)
示例12: test_decode_filename
def test_decode_filename(self):
with open(self.tmpin, 'wb') as f:
f.write(encodedtextwrapped(0o644, self.tmpout))
uu.decode(self.tmpin)
with open(self.tmpout, 'rb') as f:
s = f.read()
self.assertEqual(s, plaintext)
示例13: decodetxt
def decodetxt( text,
encoding,
charset):
#necessary due to a bug in python 3 email module
if not charset:
charset="UTF-8"
if not encoding:
encoding="8bit"
if charset!=None:
try:
"test".encode(charset)
except:
charset="UTF-8"
bytetext=text.encode(charset,unicodeerror)
result=bytetext
cte=encoding.upper()
if cte=="BASE64":
pad_err = len(bytetext) % 4
if pad_err:
padded_encoded = bytetext + b'==='[:4-pad_err]
else:
padded_encoded = bytetext
try:
result= base64.b64decode(padded_encoded, validate=True)
except binascii.Error:
for i in 0, 1, 2, 3:
try:
result= base64.b64decode(bytetext+b'='*i, validate=False)
break
except binascii.Error:
pass
else:
raise AssertionError("unexpected binascii.Error")
elif cte=="QUOTED-PRINTABLE":
result=quopri.decodestring(bytetext)
elif cte in ('X-UUENCODE', 'UUENCODE', 'UUE', 'X-UUE'):
in_file = BytesIO(bytetext)
out_file =BytesIO()
try:
uu.decode(in_file, out_file, quiet=True)
result=out_file.getvalue()
except uu.Error:
pass
return result.decode(charset,unicodeerror)
示例14: __call__
def __call__(self, path, target):
"""Decode C{path} into C{target} using the C{uu} module.
@todo: Confirm that this will always extract within C{target}"""
import uu
cwd = os.getcwd()
try:
os.chdir(target)
uu.decode(file(path, 'rb'))
finally:
os.chdir(cwd)
示例15: check_uu
def check_uu(msg, data):
assert msg._payload.encode() != data, "Payload has not been transformed"
outfile = BytesIO()
try:
uu.decode(BytesIO(msg._payload.encode()), outfile)
payload = outfile.getvalue()
except uu.Error:
assert False, "Payload could not be decoded"
assert payload == data, "Decoded payload does not match input data"
assert INBOXEN_ENCODING_ERROR_HEADER_NAME not in msg.keys(), "Unexpected error header"