Issue
Say that you have a string of bytes generated via os.urandom(24)
,
b'\x1b\xba\x94(\xae\xd0\xb2\xa6\xf2f\xf6\x1fI\xed\xbao$\xc6D\x08\xba\x81\x96v'
and you'd like to store that in an environment variable,
export FOO='\x1b\xba\x94(\xae\xd0\xb2\xa6\xf2f\xf6\x1fI\xed\xbao$\xc6D\x08\xba\x81\x96v'
and retrieve the value from within a Python program using os.environ
.
foo = os.environ['FOO']
The problem is that, here, foo
has the string literal value '\\x1b\\xba\\x94...
instead of the byte sequence b'\x1b\xba\x94...
.
What is the proper export
value to use, or means of using os.environ
to treat FOO
as a string of bytes?
Solution
You can 'unescape' your bytes in Python with:
import os
import sys
if sys.version_info[0] < 3: # sadly, it's done differently in Python 2.x vs 3.x
foo = os.environ["FOO"].decode('string_escape') # since already in bytes...
else:
foo = bytes(os.environ["FOO"], "utf-8").decode('unicode_escape')
Answered By - zwer Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.