This page shows Python examples of codecs.encode.
SearchbyModule
SearchbyWords
SearchProjects
MostPopular
TopPythonAPIs
PopularProjects
Java
Python
JavaScript
TypeScript
C++
Scala
Blog
reportthisad
Morefromcodecs
.open()
.lookup()
.getwriter()
.getreader()
.BOM_UTF16_BE
.BOM_UTF16_LE
.BOM_UTF8
.utf_8_decode()
.utf_16_be_decode()
.getencoder()
.utf_16_le_decode()
.BOM_UTF32_BE
.BOM_UTF32_LE
.StreamReader()
.register_error()
.register()
.getdecoder()
.StreamWriter()
.getincrementalencoder()
.latin_1_decode()
reportthisad
RelatedMethods
sys.exit()
sys.argv()
re.compile()
os.environ()
sys.stdout()
time.time()
os.listdir()
re.sub()
time.sleep()
os.remove()
os.makedirs()
logging.getLogger()
os.getcwd()
logging.DEBUG
sys.version_info()
json.loads()
json.dumps()
copy.deepcopy()
argparse.ArgumentParser()
codecs.decode()
RelatedModules
os
sys
re
time
logging
datetime
random
os.path
math
subprocess
shutil
json
collections
argparse
setuptools
Pythoncodecs.encode()
Examples
Thefollowingare30
codeexamplesofcodecs.encode().
Youcanvoteuptheonesyoulikeorvotedowntheonesyoudon'tlike,
andgototheoriginalprojectorsourcefilebyfollowingthelinksaboveeachexample.
Youmayalsowanttocheckoutallavailablefunctions/classesofthemodule
codecs
,ortrythesearchfunction
.
Example#1
SourceProject:
lnd_grpc
Author:willcl-ark
File:
base_client.py
License:
MITLicense
6
votes
defmacaroon(self):
"""
trytoopenthemacaroonandreturnitasabytestring
"""
try:
withopen(self.macaroon_path,"rb")asf:
macaroon_bytes=f.read()
macaroon=codecs.encode(macaroon_bytes,"hex")
returnmacaroon
exceptFileNotFoundError:
sys.stderr.write(
f"Couldnotfindmacaroonin{self.macaroon_path}.Thismighthappen"
f"inversionsoflnd0:
print("error='PAYMENTFAILED'")
print("error_detail='{}'".format(response.payment_error))
return
exceptExceptionase:
print("error='FAILEDLNDINVOICEPAYMENT'")
return
returnresponse
Example#5
SourceProject:
gipc
Author:jgehrcke
File:
gipc.py
License:
MITLicense
6
votes
def__init__(self):
global_all_handles
#Generatelabeloftext/unicodetypefromthreerandombytes.
self._id=codecs.encode(os.urandom(3),"hex_codec").decode("ascii")
self._legit_pid=os.getpid()
self._make_nonblocking()
#Definelockforsynchronizingaccesstothishandlewithinthecurrent
#process.Notethata`gevent.lock.Semaphore`instancelivesonthe
#heapofthecurrentprocessandcannotbeusedtosynchronizeaccess
#acrossmultipleprocesses.Thatis,thislockisonlymeaningfulin
#thecurrentprocess.Thisisespeciallyimportanttoconsiderwhenthe
#platformsupportsfork()ing.
self._lock=gevent.lock.Semaphore(value=1)
self._closed=False
_all_handles.append(self)
Example#6
SourceProject:
recruit
Author:Frank-qlu
File:
security.py
License:
ApacheLicense2.0
6
votes
defpbkdf2_hex(
data,salt,iterations=DEFAULT_PBKDF2_ITERATIONS,keylen=None,hashfunc=None
):
"""Like:func:`pbkdf2_bin`,butreturnsahex-encodedstring.
..versionadded::0.9
:paramdata:thedatatoderive.
:paramsalt:thesaltforthederivation.
:paramiterations:thenumberofiterations.
:paramkeylen:thelengthoftheresultingkey.Ifnotprovided,
thedigestsizewillbeused.
:paramhashfunc:thehashfunctiontouse.Thiscaneitherbethe
stringnameofaknownhashfunction,orafunction
fromthehashlibmodule.Defaultstosha256.
"""
rv=pbkdf2_bin(data,salt,iterations,keylen,hashfunc)
returnto_native(codecs.encode(rv,"hex_codec"))
Example#7
SourceProject:
yamdwe
Author:projectgus
File:
dokuwiki.py
License:
BSD3-Clause"New"or"Revised"License
6
votes
defmake_dokuwiki_pagename(mediawiki_name):
"""
Convertacanonicalmediawikipagenametoadokuwikipagename
Anynamespacingthatisintheformofa/isreplacedwitha:
"""
result=mediawiki_name.replace("","_")
#Wehavepagesthathave':'inthem-replacewithunderscores
result=result.replace(':','_')
result=names.clean_id(camel_to_underscore(result)).replace("/",":")
#Someofourmediawikipagenamesbeginwitha'/',whichresultsinos.path.joinassumingthepageisanabsolutepath.
ifresult[0]==':':
result=result.lstrip(':')
#Fixanypagesthatbeganwithaspace,becausethatbreaksdokuwiki
result=result.replace(":_",":")
result=codecs.encode(result,sys.getfilesystemencoding(),"replace")
returnresult
Example#8
SourceProject:
jbox
Author:jpush
File:
security.py
License:
MITLicense
6
votes
defpbkdf2_hex(data,salt,iterations=DEFAULT_PBKDF2_ITERATIONS,
keylen=None,hashfunc=None):
"""Like:func:`pbkdf2_bin`,butreturnsahex-encodedstring.
..versionadded::0.9
:paramdata:thedatatoderive.
:paramsalt:thesaltforthederivation.
:paramiterations:thenumberofiterations.
:paramkeylen:thelengthoftheresultingkey.Ifnotprovided,
thedigestsizewillbeused.
:paramhashfunc:thehashfunctiontouse.Thiscaneitherbethe
stringnameofaknownhashfunction,orafunction
fromthehashlibmodule.Defaultstosha1.
"""
rv=pbkdf2_bin(data,salt,iterations,keylen,hashfunc)
returnto_native(codecs.encode(rv,'hex_codec'))
Example#9
SourceProject:
macro_pack
Author:sevagas
File:
obfuscate_strings.py
License:
ApacheLicense2.0
6
votes
def_maskStrings(self,macroLines,newFunctionName):
"""MaskstringinVBAbyencodingthem"""
#Findstringsandreplacethembyhexencodedversion
forn,lineinenumerate(macroLines):
#Checkifstringisnotpreprocessorinstruction,constorcontainescapequoting
ifline.lstrip()!=""andline.lstrip()[0]!='#'and"Const"notinlineand"\"\""notinlineand"PtrSafeFunction"notinlineand"DeclareFunction"notinlineand"PtrSafeSub"notinlineand"DeclareSub"notinlineand"Environ"notinline:
#Findstringsinline
findList=re.findall(r'"(.+?)"',line,re.I)
iffindList:
fordetectedStringinfindList:
#Hexencodestring
encodedBytes=codecs.encode(bytes(detectedString,"utf-8"),'hex_codec')
newStr=newFunctionName+"(\""+encodedBytes.decode("utf-8")+"\")"
wordToReplace="\""+detectedString+"\""
line=line.replace(wordToReplace,newStr)
#Replacelineifresultisnottoobig
iflen(line)<1024:
macroLines[n]=line
returnmacroLines
Example#10
SourceProject:
credstash
Author:fugue
File:
credstash.py
License:
ApacheLicense2.0
6
votes
defseal_aes_ctr_legacy(key_service,secret,digest_method=DEFAULT_DIGEST):
"""
Encrypts`secret`usingthekeyservice.
Youcandecryptwiththecompanionmethod`open_aes_ctr_legacy`.
"""
#generateaa64bytekey.
#Halfwillbefordataencryption,theotherhalfforHMAC
key,encoded_key=key_service.generate_key_data(64)
ciphertext,hmac=_seal_aes_ctr(
secret,key,LEGACY_NONCE,digest_method,
)
return{
'key':b64encode(encoded_key).decode('utf-8'),
'contents':b64encode(ciphertext).decode('utf-8'),
'hmac':codecs.encode(hmac,"hex_codec"),
'digest':digest_method,
}
Example#11
SourceProject:
python-tabulate
Author:gregbanks
File:
benchmark.py
License:
MITLicense
6
votes
defbenchmark(n):
globalmethods
if'--onlyself'insys.argv[1:]:
methods=[mforminmethodsifm[0].startswith("tabulate")]
else:
methods=methods
results=[(desc,timeit(code,setup_code,number=n)/n*1e6)
fordesc,codeinmethods]
mintime=min(map(lambdax:x[1],results))
results=[(desc,t,t/mintime)fordesc,tin
sorted(results,key=lambdax:x[1])]
table=tabulate.tabulate(results,
[u"Tableformatter",u"time,μs",u"rel.time"],
u"rst",floatfmt=".1f")
printcodecs.encode(table,"utf-8")
Example#12
SourceProject:
lambda-packs
Author:ryfeus
File:
security.py
License:
MITLicense
6
votes
defpbkdf2_hex(data,salt,iterations=DEFAULT_PBKDF2_ITERATIONS,
keylen=None,hashfunc=None):
"""Like:func:`pbkdf2_bin`,butreturnsahex-encodedstring.
..versionadded::0.9
:paramdata:thedatatoderive.
:paramsalt:thesaltforthederivation.
:paramiterations:thenumberofiterations.
:paramkeylen:thelengthoftheresultingkey.Ifnotprovided,
thedigestsizewillbeused.
:paramhashfunc:thehashfunctiontouse.Thiscaneitherbethe
stringnameofaknownhashfunction,orafunction
fromthehashlibmodule.Defaultstosha256.
"""
rv=pbkdf2_bin(data,salt,iterations,keylen,hashfunc)
returnto_native(codecs.encode(rv,'hex_codec'))
Example#13
SourceProject:
ironpython2
Author:IronLanguages
File:
test_codecs.py
License:
ApacheLicense2.0
6
votes
deftest_bug1098990_b(self):
s1=u"aaaaaaaaaaaaaaaaaaaaaaaa\r\n"
s2=u"bbbbbbbbbbbbbbbbbbbbbbbb\r\n"
s3=u"stillokay:bbbbxx\r\n"
s4=u"broken!!!!badbad\r\n"
s5=u"againokay.\r\n"
s=(s1+s2+s3+s4+s5).encode(self.encoding)
stream=StringIO.StringIO(s)
reader=codecs.getreader(self.encoding)(stream)
self.assertEqual(reader.readline(),s1)
self.assertEqual(reader.readline(),s2)
self.assertEqual(reader.readline(),s3)
self.assertEqual(reader.readline(),s4)
self.assertEqual(reader.readline(),s5)
self.assertEqual(reader.readline(),u"")
Example#14
SourceProject:
ironpython2
Author:IronLanguages
File:
test_codecs.py
License:
ApacheLicense2.0
6
votes
deftest_ascii(self):
#SetD(directlyencodedcharacters)
set_d=('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'abcdefghijklmnopqrstuvwxyz'
'0123456789'
'\'(),-./:?')
self.assertEqual(set_d.encode(self.encoding),set_d)
self.assertEqual(set_d.decode(self.encoding),set_d)
#SetO(optionaldirectcharacters)
set_o='!"#$%&*;<=>@[]^_`{|}'
self.assertEqual(set_o.encode(self.encoding),set_o)
self.assertEqual(set_o.decode(self.encoding),set_o)
#+
self.assertEqual(u'a+b'.encode(self.encoding),'a+-b')
self.assertEqual('a+-b'.decode(self.encoding),u'a+b')
#Whitespaces
ws='\t\n\r'
self.assertEqual(ws.encode(self.encoding),ws)
self.assertEqual(ws.decode(self.encoding),ws)
#OtherASCIIcharacters
other_ascii=''.join(sorted(set(chr(i)foriinrange(0x80))-
set(set_d+set_o+'+'+ws)))
self.assertEqual(other_ascii.encode(self.encoding),
'+AAAAAQACAAMABAAFAAYABwAIAAsADAAOAA8AEAARABIAEwAU'
'ABUAFgAXABgAGQAaABsAHAAdAB4AHwBcAH4Afw-')
Example#15
SourceProject:
ironpython2
Author:IronLanguages
File:
test_codecs.py
License:
ApacheLicense2.0
6
votes
deftest_all(self):
api=(
"encode","decode",
"register","CodecInfo","Codec","IncrementalEncoder",
"IncrementalDecoder","StreamReader","StreamWriter","lookup",
"getencoder","getdecoder","getincrementalencoder",
"getincrementaldecoder","getreader","getwriter",
"register_error","lookup_error",
"strict_errors","replace_errors","ignore_errors",
"xmlcharrefreplace_errors","backslashreplace_errors",
"open","EncodedFile",
"iterencode","iterdecode",
"BOM","BOM_BE","BOM_LE",
"BOM_UTF8","BOM_UTF16","BOM_UTF16_BE","BOM_UTF16_LE",
"BOM_UTF32","BOM_UTF32_BE","BOM_UTF32_LE",
"BOM32_BE","BOM32_LE","BOM64_BE","BOM64_LE",#Undocumented
"StreamReaderWriter","StreamRecoder",
)
self.assertEqual(sorted(api),sorted(codecs.__all__))
forapiincodecs.__all__:
getattr(codecs,api)
Example#16
SourceProject:
IOTA_demo
Author:llSourcell
File:
types.py
License:
MITLicense
6
votes
defrandom(cls,length):
#type:(int)->TryteString
"""
Generatesarandomsequenceoftrytes.
:paramlength:
Numberoftrytestogenerate.
"""
alphabet=list(itervalues(AsciiTrytesCodec.alphabet))
generator=SystemRandom()
#:py:meth:`SystemRandom.choices`wasn'taddeduntilPython3.6;
#forcompatibility,wewillcontinuetouse``choice``inaloop.
#https://docs.python.org/3/library/random.html#random.choices
returncls(
''.join(chr(generator.choice(alphabet))for_inrange(length))
.encode('ascii')
)
Example#17
SourceProject:
liffy
Author:mzfr
File:
data.py
License:
GNUGeneralPublicLicensev3.0
5
votes
defexecute_data(self):
lhost,lport,shell=msf_payload()
file=join(HERE,"Server.py")
ifself.nostager:
withopen("/tmp/{0}.php".format(shell),"r")asf:
payload=f.read()
else:
payload=STAGER.format(lhost,shell)
encoded_payload=quote(codecs.encode(payload.encode("utf-8"),"base64"))
data_wrapper="data://text/html;base64,{0}".format(encoded_payload)
handle=listener(lhost,lport)
handle.handler()
ifself.nostager:
#TODO:Progressbar
pass
else:
print(colors("[~]StartingWebServer...",93))
try:
p=subprocess.Popen(["python{}".format(file)],shell=True,stdout=subprocess.PIPE)
p.communicate()
exceptOSErrorase:
print(colors("[!]ProcessError",91))
input(colors("[?]PressEnterToContinueWhenYournetcatlistenerisRunning...",94))
ifself.cookies:
cookies=cook(self.cookies)
attack(self.target,data_wrapper,cookies=cookies)
else:
attack(self.target,data_wrapper)
Example#18
SourceProject:
hadrian
Author:modelop
File:
bytes.py
License:
ApacheLicense2.0
5
votes
def__call__(self,state,scope,pos,paramTypes,x):
ifparamTypes[0]=="bytes"orparamTypes[0]=={"type":"bytes"}:
try:
codecs.decode(x,self.codec,"strict")
exceptUnicodeDecodeError:
returnFalse
else:
returnTrue
else:
try:
codecs.encode(x,self.codec,"strict")
exceptUnicodeEncodeError:
returnFalse
else:
returnTrue
Example#19
SourceProject:
hadrian
Author:modelop
File:
bytes.py
License:
ApacheLicense2.0
5
votes
def__call__(self,state,scope,pos,paramTypes,x):
try:
returncodecs.encode(x,self.codec,"strict")
exceptUnicodeEncodeError:
raisePFARuntimeException("invalidstring",self.errcodeBase+0,self.name,pos)
Example#20
SourceProject:
py-solc
Author:ethereum
File:
string.py
License:
MITLicense
5
votes
defforce_bytes(value,encoding='iso-8859-1'):
ifis_bytes(value):
returnbytes(value)
elifis_text(value):
returncodecs.encode(value,encoding)
else:
raiseTypeError("Unsupportedtype:{0}".format(type(value)))
Example#21
SourceProject:
raspiblitz
Author:rootzoll
File:
client.py
License:
MITLicense
5
votes
defconvert_r_hash(r_hash):
"""convert_r_hash
>>>convert_r_hash("+eMo9YTaZIjkJacclb6LYUocwa0q7cgVOBPf/0aclYQ=")
'f9e328f584da6488e425a71c95be8b614a1cc1ad2aedc8153813dfff469c9584'
"""
r_hash_bytes=codecs.decode(r_hash.encode(),'base64')
r_hash_hex_bytes=codecs.encode(r_hash_bytes,'hex')
returnr_hash_hex_bytes.decode()
Example#22
SourceProject:
raspiblitz
Author:rootzoll
File:
client.py
License:
MITLicense
5
votes
defconvert_r_hash_hex_bytes(r_hash_hex_bytes):
"""convert_r_hash_hex_bytes
>>>convert_r_hash_hex_bytes(b'\xf9\xe3(\xf5\x84\xdad\x88\xe4%\xa7\x1c\x95\xbe\x8baJ\x1c\xc1\xad*\xed\xc8\x158\x13\xdf\xffF\x9c\x95\x84')
'f9e328f584da6488e425a71c95be8b614a1cc1ad2aedc8153813dfff469c9584'
"""
r_hash_hex_bytes=codecs.encode(r_hash_hex_bytes,'hex')
returnr_hash_hex_bytes.decode()
Example#23
SourceProject:
raspiblitz
Author:rootzoll
File:
client.py
License:
MITLicense
5
votes
defget_rpc_channel(host="localhost",port="10009",cert_path=None,macaroon_path=None):
ifnotmacaroon_path:
raiseException("needtospecifyamacaroonpath!")
defmetadata_callback(context,callback):
#formoreinfoseegrpcdocs
callback([('macaroon',macaroon)],None)
#DuetoupdatedECDSAgeneratedtls.certweneedtoletgprcknowthat
#weneedtousethatciphersuiteotherwisetherewillbeahandshake
#errorwhenwecommunicatewiththelndrpcserver.
os.environ["GRPC_SSL_CIPHER_SUITES"]='HIGH+ECDSA'
ifnotcert_path:
cert_path=os.path.expanduser('~/.lnd/tls.cert')
assertisfile(cert_path)andos.access(cert_path,os.R_OK),\
"File{}doesn'texistorisn'treadable".format(cert_path)
cert=open(cert_path,'rb').read()
withopen(macaroon_path,'rb')asf:
macaroon_bytes=f.read()
macaroon=codecs.encode(macaroon_bytes,'hex')
#buildsslcredentialsusingthecertthesameasbefore
cert_creds=grpc.ssl_channel_credentials(cert)
#nowbuildmetadatacredentials
auth_creds=grpc.metadata_call_credentials(metadata_callback)
#combinethecertcredentialsandthemacaroonauthcredentials
#suchthateverycallisproperlyencryptedandauthenticated
combined_creds=grpc.composite_channel_credentials(cert_creds,auth_creds)
#finallypassinthecombinedcredentialswhencreatingachannel
returngrpc.secure_channel('{}:{}'.format(host,port),combined_creds)
Example#24
SourceProject:
pysat
Author:pysat
File:
demeter.py
License:
BSD3-Clause"New"or"Revised"License
5
votes
defbytes_to_float(chunk):
"""Convertachunkofbytestoafloat
Parameters
------------
chunk:stringorbytes
Achunkofbytes
Returns
--------
value:float
A32bitfloat
"""
importsys
importstruct
importcodecs
chunk_code=codecs.encode(chunk,'hex')
ifsys.version_info.major==2:
decoded=chunk_code.decode('hex')
elifhasattr(chunk_code,"decode"):
decoded=bytes.fromhex(chunk_code.decode('utf-8'))
else:
decoded=bytes.fromhex(chunk_code)
returnstruct.unpack("!f",decoded)[0]
Example#25
SourceProject:
sgd-influence
Author:sato9hara
File:
MyMNIST.py
License:
MITLicense
5
votes
defget_int(b):
returnint(codecs.encode(b,'hex'),16)
Example#26
SourceProject:
Facedancer
Author:usb-tools
File:
greathost.py
License:
BSD3-Clause"New"or"Revised"License
5
votes
def_decode_usb_register(transfer_result):
"""
Decodesaraw32-bitregistervaluefromaformencoded
fortransitasaUSBcontrolrequest.
transfer_result:Thevaluereturnedbythevendorrequest.
returns:Therawintegervalueofthegivenregister.
"""
status_hex=codecs.encode(transfer_result[::-1],'hex')
returnint(status_hex,16)
Example#27
SourceProject:
Facedancer
Author:usb-tools
File:
greatdancer.py
License:
BSD3-Clause"New"or"Revised"License
5
votes
def_decode_usb_register(transfer_result):
"""
Decodesaraw32-bitregistervaluefromaformencoded
fortransitasaUSBcontrolrequest.
transfer_result:Thevaluereturnedbythevendorrequest.
returns:Therawintegervalueofthegivenregister.
"""
status_hex=codecs.encode(transfer_result[::-1],'hex')
returnint(status_hex,16)
Example#28
SourceProject:
recruit
Author:Frank-qlu
File:
security.py
License:
ApacheLicense2.0
5
votes
defsafe_str_cmp(a,b):
"""Thisfunctioncomparesstringsinsomewhatconstanttime.This
requiresthatthelengthofatleastonestringisknowninadvance.
Returns`True`ifthetwostringsareequal,or`False`iftheyarenot.
..versionadded::0.7
"""
ifisinstance(a,text_type):
a=a.encode("utf-8")
ifisinstance(b,text_type):
b=b.encode("utf-8")
if_builtin_safe_str_cmpisnotNone:
return_builtin_safe_str_cmp(a,b)
iflen(a)!=len(b):
returnFalse
rv=0
ifPY2:
forx,yinizip(a,b):
rv|=ord(x)^ord(y)
else:
forx,yinizip(a,b):
rv|=x^y
returnrv==0
Example#29
SourceProject:
recruit
Author:Frank-qlu
File:
security.py
License:
ApacheLicense2.0
5
votes
def_hash_internal(method,salt,password):
"""Internalpasswordhashhelper.Supportsplaintextwithoutsalt,
unsaltedandsaltedpasswords.Incasesaltedpasswordsareused
hmacisused.
"""
ifmethod=="plain":
returnpassword,method
ifisinstance(password,text_type):
password=password.encode("utf-8")
ifmethod.startswith("pbkdf2:"):
args=method[7:].split(":")
iflen(args)notin(1,2):
raiseValueError("InvalidnumberofargumentsforPBKDF2")
method=args.pop(0)
iterations=argsandint(args[0]or0)orDEFAULT_PBKDF2_ITERATIONS
is_pbkdf2=True
actual_method="pbkdf2:%s:%d"%(method,iterations)
else:
is_pbkdf2=False
actual_method=method
ifis_pbkdf2:
ifnotsalt:
raiseValueError("SaltisrequiredforPBKDF2")
rv=pbkdf2_hex(password,salt,iterations,hashfunc=method)
elifsalt:
ifisinstance(salt,text_type):
salt=salt.encode("utf-8")
mac=_create_mac(salt,password,method)
rv=mac.hexdigest()
else:
rv=hashlib.new(method,password).hexdigest()
returnrv,actual_method
Example#30
SourceProject:
bgd
Author:igolan
File:
datasets.py
License:
MITLicense
5
votes
defget_int(b):
returnint(codecs.encode(b,'hex'),16)
reportthisad