Can we send config file as parameter to python

python

#1

Hi,
I have a requirement that need to run the 10 configurations file by single script
Currently my approach is the same code is reading the single config file, so I am copy paste the code and making the config file entry in the python code and run. – this runs

Now I am thinking to make this config file as parameter.

Example: python script.py configfile.py

this works but i am using the code like to import the config file.as showed below.
config=sys.argv[1]
import config as cfg

this fails as –
import config as cfg
ImportError: No module named ‘config’

Any help is much appreciated.

Thanks,
Sachin


#2

from my practical experience:
I created a static class with nested dictionary to enable dynamic configurations for my main code to consume. In that manner i was able to import the file as a module and able to access the configuration objects.

Something like:
model_definitions = {
“config1”:{
“batch_size” : 128,
“epochs”: 10
},
“config2”:{
“batch_size” : 64,
“epochs”: 10
}
}


#3

Maintain one main config file where you mentioned 10 config files path, just read main config file and do your operation like file reading of 10 files, it will be good if those 10 fikes are dict or json format


#4

Hi @sachin123456,
you need to add the following lines in script.py to import the config file.

file = sys.argv[1].split(".")[0]
config = __import__(file)

import statement requires the filename without the .py extension. to access any variable defined inside configfile.py, just use config.var.

For more information refer to this link on import-confusion.

Hope this helps.:smile: