Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set a string of bytes from an environment variable in Python?

Tags:

python

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?

like image 938
ybakos Avatar asked Jun 11 '17 02:06

ybakos


1 Answers

The easiest option is to simply set it as binary data in Bash. This uses ANSI string quoting and avoids the need for any sort of conversion on the Python side.

export FOO=$'\x1b\xba\x94(\xae\xd0\xb2\xa6\xf2f\xf6\x1fI\xed\xbao$\xc6D\x08\xba\x81\x96v'
like image 175
miken32 Avatar answered Sep 21 '22 14:09

miken32