Home > Mobile >  Dynamically import a python file whose name is stored in a variable
Dynamically import a python file whose name is stored in a variable

Time:08-11

I have 2 python scripts. First python script name is "test_1.py" and internally it has main() function, and second script is "test_2.py" and internally it has a method called "sub_main()". Like wise I can have

test_3.py, test_4.py etc

Now in my "test_1.py I am trying to import "test_2.py" dynamically i.e the user will send the file name in command line arguments and I will store it in a variable and using this variable I should be able to import that respective script and call the "sub_main()" in my "main()" method of "test_1.py". Is there a workaround for this?

CodePudding user response:

You can use:

import importlib

module_name = input('Enter a module name you want')
dynamically_imported_module = importlib.import_module(module_name)

CodePudding user response:

You can obtain the name of the module you want to import from the command line arguments, put it into a variable, use that in an f string and exec() that f string:

st = f"import {name_of_module_to_be_imported}"
exec(st)

Whether that is a good idea is, of course, another question. You're opening yourself up to all sorts of security exploits where somebody could inject malicious code into the command-line arguments, which you will then execute.

  • Related