Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I import a python module from a string in memory?

Tags:

python

I have a string of a python module stored in a variable (creds) that looks like this:

MY_API_KEY = "DerP12312"
ANOTHER_KEY = "123453)"

(Many more lines than just the 2, but all the same convention)

I'd like to import the values of that module into another class like so:

from creds import MY_API_KEY

A limitation is that I cannot write these contents to local storage. (I'd prefer not to do string disection based on /n and =)

Can I import these values directly from memory?

like image 217
Dan O'Boyle Avatar asked Apr 17 '26 23:04

Dan O'Boyle


1 Answers

Yep, you can use the exec function to execute a string of Python source code (by default it's executed in the current scope so those variables will be set globally):

>>> exec('MY_API_KEY = "DerP12312"\nANOTHER_KEY = "123453)"\n')
>>> MY_API_KEY
'DerP12312'
>>> ANOTHER_KEY
'123453)'
like image 105
Ben Hoyt Avatar answered Apr 19 '26 11:04

Ben Hoyt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!