Reputation: 221
I have 2 scripts, say test.py
and main.py
.
My test.py
contains only dictionaries (No other code).
I am running main.py
by passing dict_name as a argument. Here I want to fetch the dict passed as argument from test.py
and display it's content in main.py
.
test.py
config_123={"name":"Dave","age":25}
config_89033 = {"name":"alex","age":30}
.....
To run main.py
(Note: here I am passing 1st argument with dots)
python main.py 1.2.3
main.py
import sys
from test import *
if __name__ == '__main__':
if len(sys.argv) != 2:
print "error message"
sys.exit(1)
else:
dict_name=sys.argv[1]
#if dict_name contains '.' , replace it
if '.' in dict_name:
temp_name=dict_name.replace(".","") #gives me 123
else:
temp_name = dict_name
#here i want to print the content of dict from test.py
print config_123 #it prints dict (as i am importing * from test)
#but i need to create it dynamically.
print "config_"+temp_name #obviously it prints it as a string "config_123"
#how should i call it here?
In this case, how can I call config_123
from test.py
and display the dict?
Upvotes: 1
Views: 147
Reputation: 109686
You could also store the configs as a single dictionary keyed off of their name and then get them from there.
test.py
=======
configs = {'config_123': {"name":"Dave","age":25},
'config_89033': {"name":"alex","age":30}}
main.py
=======
from test import configs
config = configs.get('config_123')
Upvotes: 1
Reputation: 2662
I'm not sure if this is the best way, but it seems to work.
You can use the built-in locals() function to get any local variables as a dictionary. Then, the get function for a dict seems to get the correct config:
import sys, test
dname = sys.argv[1]
config1 = {'name':'Bob'}
config2 = {'name':'Alice'}
#if the variable is local
print locals().get(dname, None)
#if it's in the test module
#config = getattr(test, dname)
The output looks like this:
python main.py config2
{'name': 'Alice'}
python main.py config1
{'name': 'Bob'}
Upvotes: 1
Reputation: 85522
Import the module with import test
and use getattr()
on the module:
import test
print getattr(test, 'config_123')
Output:
{'age': 25, 'name': 'Dave'}
Or in your case:
print getattr(test, 'config_' + temp_name )
Upvotes: 1