[FIXED] Dynamically import a python file whose name is stored in a variable

Issue

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?


Solution

You can use:

import importlib

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


Answered By - Daniel Agam
Answer Checked By - Senaida (Python.Easybugfix Volunteer)

Related Posts

Post a Comment