0

I am very new to python and have a project in which I am working on the following:

I have 2 py config files with multiple parameters inside them. They named config_default and config_custom both with the function name def config().

Config default has predefined parameters and for config_custom.py, the parameters are passed from the command line arguments.

Problem:

To choose between these two files when the main script with variable number of arguments is executed.

  1. If the argument has length = 1, then choose config_default and all the other python scripts in the project uses parameters from config() of config_default whenever imported.
  2. If it has more arguments, corresponding values must be assigned to parameters in the function config() of config_custom.

What I tried:

I tried using *args and checked the length of arguments and assigned file path to variable named config. Then trying to import it in all the scripts, but it doesn't work.

Here is the snippet.

def main(*args):
args = sys.argv[1:]
if (len(sys.argv) == 1):
    input1= sys.argv[0]
    config_file = "./config_default.py"
elif (len(sys.argv) == 3):
    input1= sys.argv[0]
    input2= sys.argv[1]
    input3= sys.argv[2]
    config_file = "./config_custom.py"
else:
    print("Error: Check the arguments")
    sys.exit()

Then using "import config" to import.

The error is: ModuleNotFoundError: No module named 'config'

Triuare
  • 1
  • 1
  • Config files should not contain arbitrary Python code. Having said that, you can dynamically import different modules by placing the `import` statement in a conditionally executed block. I have no idea why you think defining a `config_file` variable would affect a `import config` statement. What did you read that gave you that idea? – Kurtis Rader Sep 08 '22 at 04:04
  • @KurtisRader Thank you. I imported the config files and it works fine. But out of curiosity, can we import non-python modules? I googled a bit and found that we can't import non- *.py? Is there any alternative to this? for example, importing a .json or .txt directly to use the variables inside them? Currently I am using: `from config_default import config as config` – Triuare Sep 28 '22 at 21:57

0 Answers0